No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Computer, Inc. Printed in the United States of America.
No licenses, express or implied, are granted with respect to any of the technology described in this book. Apple retains all intellectual property rights associated with the technology described in this book. This book is intended to assist application developers to develop applications only for Apple Macintosh computers.
Apple Computer, Inc.
20525 Mariani Avenue
Cupertino, CA 95014
408-996-1010
Apple, the Apple logo, APDA, AppleLink, AppleTalk, LaserWriter, Macintosh, MPW, and SANE are trademarks of Apple Computer, Inc., registered in the United States and other countries.
AppleScript, Finder, Moof, New York, QuickDraw, QuickTime, and System 7 are trademarks of Apple Computer, Inc.
Adobe Illustrator, Adobe Photoshop, and PostScript are trademarks of Adobe Systems Incorporated, which may be registered in certain jurisdictions.
America Online is a service mark of Quantum Computer Services, Inc.
CompuServe is a registered trademark of CompuServe, Inc.
FrameMaker is a registered trademark of Frame Technology Corporation.
Helvetica, Palatino, and Times are registered trademarks of Linotype Company.
HyperCard and HyperTalk are registered trademarks of Claris Corporation.
Internet is a trademark of Digital Equipment Corporation.
ITC Zapf Dingbats is a registered trademark of International Typeface Corporation.
Optrotech is a trademark of Orbotech Corporation.
Simultaneously published in the United States and Canada.
LIMITED WARRANTY ON MEDIA AND REPLACEMENT
ALL IMPLIED WARRANTIES ON THIS MANUAL, INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE LIMITED IN DURATION TO NINETY (90) DAYS FROM THE DATE OF THE ORIGINAL RETAIL PURCHASE OF THIS PRODUCT.
Even though Apple has reviewed this manual, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS MANUAL, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS MANUAL IS SOLD “AS IS,” AND YOU, THE PURCHASER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY.
IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS MANUAL, even if advised of the possibility of such damages.
THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty.
Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.
Contents
Figures, Tables, and Listingsxv
Preface About This Bookxxiii
Format of a Typical Chapterxxiv
Conventions Used in This Bookxxv
Special Fontsxxv
Types of Notesxxv
Assembly-Language Informationxxvi
The Development Environmentxxvi
Chapter 1 Introduction to Interapplication Communication1-1
Overview of Interapplication Communication1-3
Sharing Data Among Applications1-6
Sending and Responding to Apple Events1-9
Standard Apple Events1-10
Handling Apple Events1-12
Supporting AppleScript and Other Scripting Languages1-13
Scriptable Applications1-16
Recordable Applications1-18
Applications That Manipulate and Execute Scripts1-19
Exchanging Message Blocks1-22
Chapter 2 Edition Manager2-1
Introduction to Publishers, Subscribers, and Editions2-4
About the Edition Manager2-12
Using the Edition Manager2-12
Receiving Apple Events From the Edition Manager2-13
Creating the Section Record and Alias Record2-15
Saving a Document Containing Sections2-19
Opening and Closing a Document Containing Sections2-22
Reading and Writing a Section2-24
Formats in an Edition2-24
Opening an Edition2-26
Format Marks2-27
Reading and Writing Edition Data2-27
Closing an Edition2-28
Creating a Publisher2-29
Creating the Edition Container2-32
Opening an Edition Container to Write Data2-35
Creating a Subscriber2-37
Opening an Edition Container to Read Data2-41
Choosing Which Edition Format to Read2-41
Using Publisher and Subscriber Options2-43
Publishing a New Edition While Saving or Manually2-47
Subscribing to an Edition Automatically or Manually2-48
Canceling Sections Within Documents2-48
Locating a Publisher Through a Subscriber2-49
Renaming a Document Containing Sections2-50
Displaying Publisher and Subscriber Borders2-50
Text Borders2-54
Spreadsheet Borders2-55
Object-Oriented Graphics Borders2-56
Bitmapped Graphics Borders2-57
Duplicating Publishers and Subscribers2-58
Modifying a Subscriber2-59
Relocating an Edition2-60
Customizing Dialog Boxes2-60
Subscribing to Non-Edition Files2-62
Getting the Current Edition Opener2-63
Setting an Edition Opener2-63
Calling an Edition Opener2-64
Opening and Closing Editions2-68
Listing Files That Can Be Subscribed To2-68
Reading From and Writing to Files2-68
Calling a Format I/O Function2-68
Edition Manager Reference2-71
Data Structures2-71
The Edition Container Record2-71
The Section Record2-72
Edition Manager Routines2-73
Initializing the Edition Manager2-74
Creating and Registering a Section2-74
Creating and Deleting an Edition Container2-79
Setting and Getting a Format Mark2-81
Reading in Edition Data2-83
Writing out Edition Data2-86
Closing an Edition After Reading or Writing2-88
Displaying Dialog Boxes2-90
Locating a Publisher and Edition From a Subscriber2-98
Edition Container Formats2-101
Reading and Writing Non-Edition Files2-102
Application-Defined Routines2-105
Summary of the Edition Manager2-106
Pascal Summary2-106
Constants2-106
Data Types2-108
Edition Manager Routines2-111
Application-Defined Routines2-113
C Summary2-114
Constants2-114
Data Types2-116
Edition Manager Routines2-119
Application-Defined Routines2-122
Result Codes2-122
Chapter 3 Introduction to Apple Events3-1
About Apple Events3-3
Apple Events and Apple Event Objects3-6
Apple Event Attributes and Parameters3-7
Apple Event Attributes3-8
Apple Event Parameters3-9
Interpreting Apple Event Attributes and Parameters3-10
Data Structures Within Apple Events3-12
Descriptor Records3-12
Keyword-Specified Descriptor Records3-15
Descriptor Lists3-16
Responding to Apple Events3-20
Accepting and Processing Apple Events3-20
About Apple Event Handlers3-23
Extracting and Checking Data3-23
Interacting With the User3-25
Performing the Requested Action and Returning a Result3-25
Creating and Sending Apple Events3-28
Creating an Apple Event Record3-29
Adding Apple Event Attributes and Parameters3-29
Sending an Apple Event and Handling the Reply3-30
Working With Object Specifier Records3-32
Data Structures Within an Object Specifier Record3-34
The Classification of Apple Event Objects3-39
Object Classes3-39
Properties and Elements3-42
Finding Apple Event Objects3-46
About the Apple Event Manager3-48
Supporting Apple Events as a Server Application3-48
Supporting Apple Events as a Client Application3-49
Supporting Apple Event Objects3-49
Supporting Apple Event Recording3-50
Chapter 4 Responding to Apple Events4-1
Handling Apple Events4-4
Accepting an Apple Event4-5
Installing Entries in the Apple Event Dispatch Tables4-7
Installing Entries for the Required Apple Events4-8
Installing Entries for Apple Events Sent by the Edition Manager4-9
How Apple Event Dispatching Works4-9
Handling the Required Apple Events4-11
Required Apple Events4-11
Handling the Open Application Event4-14
Handling the Open Documents Event4-15
Handling the Print Documents Event4-17
Handling the Quit Application Event4-19
Handling Apple Events Sent by the Edition Manager4-20
The Section Read, Section Write, and Section Scroll Events4-21
Handling the Create Publisher Event4-22
Getting Data Out of an Apple Event4-25
Getting Data Out of an Apple Event Parameter4-26
Getting Data Out of an Attribute4-28
Getting Data Out of a Descriptor List4-31
Writing Apple Event Handlers4-33
Replying to an Apple Event4-36
Disposing of Apple Event Data Structures4-39
Writing and Installing Coercion Handlers4-41
Interacting With the User4-45
Setting the Client Application’s User Interaction Preferences4-46
Setting the Server Application’s User Interaction Preferences4-48
Requesting User Interaction4-49
Reference to Responding to Apple Events4-56
Data Structures Used by the Apple Event Manager4-56
Descriptor Records and Related Data Structures4-56
Apple Event Array Data Types4-60
Routines for Responding to Apple Events4-61
Creating and Managing the Apple Event Dispatch Tables4-61
Dispatching Apple Events4-66
Getting Data or Descriptor Records Out of Apple Event Parameters and Attributes4-68
Counting the Items in Descriptor Lists4-74
Getting Items From Descriptor Lists4-74
Getting Data and Keyword-Specified Descriptor Records Out of AE Records4-78
Requesting User Interaction4-81
Requesting More Time to Respond to Apple Events4-84
Suspending and Resuming Apple Event Handling4-85
Getting the Sizes and Descriptor Types of Descriptor Records4-89
Deleting Descriptor Records4-92
Deallocating Memory for Descriptor Records4-93
Coercing Descriptor Types4-94
Creating and Managing the Coercion Handler Dispatch Tables4-96
Creating and Managing the Special Handler Dispatch Tables4-99
Getting Information About the Apple Event Manager4-103
Application-Defined Routines4-104
Summary of Responding to Apple Events4-108
Pascal Summary4-108
Constants4-108
Data Types4-112
Routines for Responding to Apple Events4-114
Application-Defined Routines4-118
C Summary4-118
Constants4-118
Data Types4-123
Routines for Responding to Apple Events4-124
Application-Defined Routines4-128
Assembly-Language Summary4-128
Trap Macros4-128
Result Codes4-130
Chapter 5 Creating and Sending Apple Events5-1
Creating an Apple Event5-3
Adding Parameters to an Apple Event5-5
Specifying Optional Parameters for an Apple Event5-7
Specifying a Target Address5-10
Creating an Address Descriptor Record5-11
Addressing an Apple Event for Direct Dispatching5-13
Sending an Apple Event5-13
Dealing With Timeouts5-20
Writing an Idle Function5-21
Writing a Reply Filter Function5-24
Reference to Creating and Sending Apple Events5-24
Routines for Creating and Sending Apple Events5-25
Creating Apple Events5-25
Creating and Duplicating Descriptor Records5-26
Creating Descriptor Lists and AE Records5-28
Adding Items to Descriptor Lists5-29
Adding Data and Descriptor Records to AE Records5-32
Adding Parameters and Attributes to Apple Events5-33
Sending Apple Events5-37
Application-Defined Routines5-41
Summary of Creating and Sending Apple Events5-44
Pascal Summary5-44
Constants5-44
Data Types5-48
Routines for Creating and Sending Apple Events5-50
Application-Defined Routines5-51
C Summary5-51
Constants5-51
Data Types5-56
Routines for Creating and Sending Apple Events5-57
Application-Defined Routines5-59
Assembly-Language Summary5-59
Trap Macros5-59
Result Codes5-60
Chapter 6 Resolving and Creating Object Specifier Records6-1
Resolving Object Specifier Records6-4
Descriptor Records Used in Object Specifier Records6-8
Object Class6-9
Container6-9
Key Form6-11
Key Data6-12
Key Data for a Property ID6-13
Key Data for an Object’s Name6-14
Key Data for a Unique ID6-14
Key Data for Absolute Position6-14
Key Data for Relative Position6-15
Key Data for a Test6-15
Key Data for a Range6-20
Installing Entries in the Object Accessor Dispatch Tables6-21
Installing Object Accessor Functions That Find Apple Event Objects6-23
Installing Object Accessor Functions That Find Properties6-27
Writing Object Accessor Functions6-28
Writing Object Accessor Functions That Find Apple Event Objects6-29
Writing Object Accessor Functions That Find Properties6-37
Defining Tokens6-39
Handling Whose Tests6-41
Writing Object Callback Functions6-45
Writing an Object-Counting Function6-48
Writing an Object-Comparison Function6-50
Writing Marking Callback Functions6-53
Creating Object Specifier Records6-55
Creating a Simple Object Specifier Record6-57
Specifying the Container Hierarchy6-61
Specifying a Property6-63
Specifying a Relative Position6-64
Creating a Complex Object Specifier Record6-64
Specifying a Test6-64
Specifying a Range6-72
Reference to Resolving and Creating Object Specifier Records6-75
Data Structures Used in Object Specifier Records6-75
Routines for Resolving and Creating Object Specifier Records6-77
Initializing the Object Support Library6-77
Setting Object Accessor Functions and Object Callback Functions6-77
Getting, Calling, and Removing Object Accessor Functions6-81
Resolving Object Specifier Records6-85
Deallocating Memory for Tokens6-87
Creating Object Specifier Records6-88
Application-Defined Routines6-94
Object Accessor Functions6-94
Object Callback Functions6-96
Summary of Resolving and Creating Object Specifier Records6-104
Pascal Summary6-104
Constants6-104
Data Types6-106
Routines for Resolving and Creating Object Specifier Records6-106
Application-Defined Routines6-108
C Summary6-109
Constants6-109
Data Types6-111
Routines for Resolving and Creating Object Specifier Records6-112
Application-Defined Routines6-114
Assembly-Language Summary6-115
Trap Macros6-115
Result Codes6-115
Chapter 7 Introduction to Scripting7-1
About Scripts and Scripting Components7-4
Script Editors and Script Files7-6
Scripting Components and Scriptable Applications7-8
Scripting Components and Applications That Execute Scripts7-11
Making Your Application Scriptable7-14
About Apple Event Terminology Resources7-15
How AppleScript Uses Terminology Information7-17
Dynamic Loading of Terminology Information7-20
Making Your Application Recordable7-20
Manipulating and Executing Scripts7-22
Compiling, Saving, Modifying, and Executing Scripts7-24
Using a Script Context to Handle an Apple Event7-25
Chapter 8 Apple Event Terminology Resources8-1
Defining Terminology for Use by the AppleScript Component8-3
Structure of Apple Event Terminology Resources8-8
Creating an Apple Event Terminology Extension Resource8-13
Supporting Standard Suites Without Extensions8-14
Extending the Standard Suites8-16
Supporting Subsets of Suites8-23
Supporting New Suites8-23
Handling the Get AETE Event8-23
Reference to Apple Event Terminology Resources8-26
Header Data for an Apple Event Terminology Resource8-27
Suite Data for an Apple Event Terminology Resource8-27
Event Data8-29
Object Class Data8-36
Comparison Operator Data8-42
Enumeration and Enumerator Data8-43
The Scripting Size Resource8-45
Chapter 9 Recording Apple Events9-1
About Recordable Applications9-3
Factoring Your Application for Recording9-6
Factoring the Quit Command and the New Command9-6
Sending Apple Events Without Executing Them9-12
What to Record9-14
Recording User Actions9-15
Recording the Selection of Text Objects9-18
Recording Insertion Points9-23
Recording Typing9-27
Recording the Selection of Nontext Objects9-30
Identifying Objects9-32
Moving the Selection During Recording9-34
Recording Interactions With Dialog Boxes9-35
How Apple Event Recording Works9-35
Chapter 10 Scripting Components10-1
Connecting to a Scripting Component10-3
Using Scripting Component Routines10-7
Compiling and Executing Source Data10-7
Saving Script Data10-12
Storage Formats for Script Data10-12
Resource and File Types for Script Data10-13
Loading and Executing Script Data10-14
Modifying and Recompiling a Compiled Script10-17
Using a Script Context to Handle an Apple Event10-19
Supplying a Resume Dispatch Function10-21
Supplying an Alternative Active Function10-23
Supplying Alternative Create and Send Functions10-24
Alternative Create Functions10-24
Alternative Send Functions10-25
Recording Scripts10-26
Writing a Scripting Component10-27
Scripting Components Reference10-28
Data Structures10-29
Required Scripting Component Routines10-30
Saving and Loading Script Data10-30
Executing and Disposing of Scripts10-33
Setting and Getting Script Information10-41
Manipulating the Active Function10-45
Optional Scripting Component Routines10-46
Compiling Scripts10-47
Getting Source Data10-51
Coercing Script Values10-52
Manipulating the Create and Send Functions10-55
Recording Scripts10-59
Executing Scripts in One Step10-61
Manipulating Dialects10-67
Using Script Contexts to Handle Apple Events10-71
AppleScript Component Routines10-80
Initializing AppleScript10-80
Getting and Setting Styles for Source Data10-82
Generic Scripting Component Routines10-84
Getting and Setting the Default Scripting Component10-86
Using Component-Specific Routines10-87
Routines Used by Scripting Components10-92
Manipulating Trailers for Generic Storage Descriptor Records10-92
Figure 11-1 A PPC Toolbox session between two applications11-5
Figure 11-2 The icon for the Sharing Setup control panel11-6
Figure 11-3 The Sharing Setup control panel11-6
Figure 11-4 The session termination alert box11-7
Figure 11-5 The users and groups dialog box11-8
Figure 11-6 The user termination alert box11-8
Figure 11-7 The guest dialog box11-9
Figure 11-8 The PPC Toolbox authentication process11-10
Figure 11-9 Database and spreadsheet applications using the PPC Toolbox11-13
Figure 11-10 Two Macintosh applications and their corresponding ports11-18
Figure 11-11 The PPC Toolbox and a dictionary service application11-20
Figure 11-12 The program linking dialog box11-22
Figure 11-13 The program linking dialog box without a zone list11-23
Figure 11-14 The user identity dialog box11-30
Figure 11-15 The incorrect password dialog box11-31
Figure 11-16 The invalid user name dialog box11-31
Figure 11-17 Transmitting message blocks11-40
Figure 11-18 The PPC Toolbox parameter blocks11-47
Listing 11-1 Initializing the PPC Toolbox using the PPCInit function11-12
Listing 11-2 Opening a PPC port11-21
Listing 11-3 Using a port filter function11-24
Listing 11-4 Browsing through dictionary service ports11-26
Listing 11-5 Using the IPCListPorts function to obtain a list of ports11-28
Listing 11-6 Using the StartSecureSession function to establish a session11-32
Listing 11-7 Initiating a session using the PPCStart function11-34
Listing 11-8 Using the PPCInform function to enable a port to receive sessions11-36
Listing 11-9 Completion routine for a PPCInform function11-37
Listing 11-10 Accepting a session request using the PPCAccept function11-38
Listing 11-11 Completion routine for a PPCAccept function11-38
Listing 11-12 Rejecting a session request using the PPCReject function11-39
Listing 11-13 Completion routine for a PPCReject function11-39
Listing 11-14 Using the PPCRead function to read data during a session11-41
Listing 11-15 Polling the ioResult field to determine if a PPCRead function has completed11-41
Listing 11-16 Using the PPCWrite function to write data during a session11-42
Listing 11-17 Polling the ioResult field to determine if a PPCWrite function has completed11-43
Listing 11-18 Ending a PPC session using the PPCEnd function11-43
Listing 11-19 Closing a PPC port using the PPCClose function11-44
Listing 11-20 Using the DeleteUserIdentity function to invalidate a user identity11-45
Chapter 12 Data Access Manager12-1
Figure 12-1 A connection with a database12-6
Figure 12-2 Using high-level Data Access Manager routines12-8
Figure 12-3 Using low-level Data Access Manager routines12-10
Figure 12-4 A flowchart of a session using the high-level interface12-15
Figure 12-5 A flowchart of a session using the low-level interface12-29
Figure 12-6 A query document dialog box12-47
Figure 12-7 The relationship between resources in a query document and the query record12-49
Figure 12-8 The relationship between a query definition function and queries12-50
Figure 12-9 Structure of a compiled query ('qrsc') resource12-90
Figure 12-10 Structure of a compiled query string ('wstr') resource12-91
Table 12-1 Data types defined by the Data Access Manager12-38
Listing 12-1 Using the high-level interface12-18
Listing 12-2 Two completion routines12-21
Listing 12-3 A sample status routine12-26
Listing 12-4 Sending a query fragment12-31
Listing 12-5 Using the low-level interface12-33
Listing 12-6 A result handler12-45
Listing 12-7 A query definition function12-52
About This Book
This book, Inside Macintosh: Interapplication Communication, describes the interapplication communication architecture, which provides a standard and extensible mechanism for communication among Macintosh applications. This book also describes the system software routines that you can use to implement various forms of interapplication communication in your application.
If you are new to programming on the Macintosh computer, you should read Inside Macintosh: Overview for an introduction to general concepts of Macintosh programming; Inside Macintosh: Macintosh Toolbox Essentials for information on how to use menus, windows, and controls in your application; and Macintosh Human Interface Guidelines for a complete discussion of user interface guidelines and principles that every Macintosh application should follow.
This book describes how to implement publish and subscribe features in your application, how to communicate with other applications using Apple events, how to respond to scripts, and how to exchange information with other applications using the PPC Toolbox. It also discusses how your application can use the Data Access Manager to access information from a database application or other data source.
For an overview of all the features provided by the interapplication communication architecture, see the chapter “Introduction to Interapplication Communication” in this book.
To provide support for publish and subscribe features in your application, see the chapter “Edition Manager” in this book. This chapter describes how your application can allow users to share dynamic data among many documents.
To communicate with other applications by using Apple events, first see the chapter “Introduction to Apple Events” for a general introduction to Apple events. For information on how to respond to the required Apple events, see the chapter “Responding to Apple Events.” To create and send Apple events, see the chapter “Creating and Sending Apple Events.”
You can choose to write your application so that it can recognize descriptions, in Apple events, of objects in the application such as words, paragraphs, shapes, or documents. To do so, see the chapter “Resolving and Creating Object Specifier Records.”
In addition to supporting Apple events, you can make your application scriptable—that is, capable of responding to Apple events sent to it by a scripting component. By executing scripts, users of scriptable applications can automate repetitive tasks or conditional tasks that involve multiple applications. For more general information about scripting, see the chapter “Introduction to Scripting.” See the chapter “Apple Event Terminology Resources” for information on the resources your application needs to provide in order to be scriptable.
You can also make your application recordable, that is, capable of recording a user’s actions for later playback. For more information, see the chapter “Recording Apple Events.”
For information on how your application can execute a script with the aid of a scripting component, see the chapter “Scripting Components.”
Although you’ll usually want to use Apple events to communicate with other applications, if you need low-level control of communication between applications you can use the Program-to-Program Communications (PPC) Toolbox. For more information, see the chapter “Program-to-Program Communications Toolbox.”
Applications can use the Data Access Manager to access information from a database application or other data source. For example, a user in San Francisco might use a spreadsheet application to request data from a company database in New York. The spreadsheet application can use the Data Access Manager to request the data from the database. The database application in New York sends back the requested data, and the spreadsheet application can then use this data to generate a graph of the information. For information on sending and retrieving information from a data source, see the chapter “Data Access Manager.”
For definitions of specific Apple events and Apple event objects, see the Apple Event Registry: Standard Suites, available from APDA.
For information on handling files in your application and a description of aliases and alias records, see Inside Macintosh: Files.
For information on processes and process serial numbers, see Inside Macintosh: Processes.
Format of a Typical Chapter
Almost all chapters in this book follow a standard structure. For example, the chapter “Creating and Sending Apple Events” contains these sections:
n “Creating an Apple Event” and “Sending an Apple Event.” These sections describe how your application can create and send Apple events. They describe the Apple Event Manager routines that you can use to accomplish these tasks, give related user interface information, and provide code samples and additional information.
n “Reference to Creating and Sending Apple Events.” This section provides a complete reference to the Apple Event Manager routines you can use to create and send Apple events. Each routine description also follows a standard format, which presents the routine declaration followed by a description of every parameter of the routine. Some routine descriptions also give additional descriptive information, such as assembly-language information or result codes.
n “Summary of Creating and Sending Apple Events.” This section provides the Pascal and C interfaces for the constants, data structures, routines, and result codes associated with the Apple Event Manager routines for creating and sending Apple events. It also includes relevant assembly-language interface information.
Conventions Used in This Book
Inside Macintosh uses various conventions to present information. Words that require special treatment appear in specific fonts or font styles. Certain information, such as the contents of registers, use special formats so that you can scan them quickly.
Special Fonts
All code listings, reserved words, and the names of actual data structures, fields, constants, parameters, and routines are shown in Courier (this is Courier).
Words that appear in boldface are key terms or concepts and are defined in the Glossary.
Types of Notes
There are several types of notes used in this book.
Note
A note like this contains information that is interesting but possibly not essential to an understanding of the main text. (An example appears on page 3-26.)u
IMPORTANT
A note like this contains information that is essential for an understanding of the main text. (An example appears on page 3-33.)s
sWARNING
Warnings like this indicate potential problems that you should be aware of as you design your application. Failure to heed these warnings could result in system crashes or loss of data. (An example appears on page page 4-10.)s
Assembly-Language Information
Some chapters provide additional assembly-language information. For example, Inside Macintosh provides information about the registers for specific routines like this:
Registers on entry
A0 Contents of register A0 on entry
Registers on exit
D0 Contents of register D0 on exit
In addition, Inside Macintosh provides information about the fields of a parameter block in this format:
´ inAndOut Integer Input/output parameter.
¨ output1 Ptr Output parameter.
Æ input1 Ptr Input parameter.
The arrow in the far left column indicates whether the field is an input parameter, output parameter, or both. You must supply values for all input parameters and input/output parameters. The routine returns values in output parameters and input/output parameters.
The second column shows the field name as defined in the MPW Pascal interface files; the third column indicates the Pascal data type of that field. The fourth column provides a brief description of the use of the field. For a complete description of each field, see the discussion that follows the parameter block or the description of the parameter block in the reference section of the chapter.
The Development Environment
The system software routines described in this book are available using Pascal, C, or assembly-language interfaces. How you access these routines depends on the development environment you are using. When showing system software routines, this book uses the Pascal interface available with the Macintosh Programmer’s Workshop (MPW).
All code listings in this book are shown in Pascal (except for listings that describe resources, which are shown in Rez-input format). They show methods of using various routines and illustrate techniques for accomplishing particular tasks. All code listings have been compiled and, in many cases, tested. However, Apple Computer, Inc., does not intend for you to use these code samples in your application. You can find the location of code listings in the list of figures, tables, and listings. If you know the name of a particular routine (such as MyHandleODoc or MyHandleQuit) shown in a code listing, you can find the page on which the routine occurs by looking under the entry “sample routines” in the index of this book.
In order to make the code listings in this book more readable, they show only limited error handling. You need to develop your own techniques for handling errors.
This book occasionally illustrates concepts by reference to sample applications called SurfWriter, SurfDB, and SurfCharter; these are not actual products of Apple Computer, Inc.
APDA is Apple’s worldwide source for over three hundred development tools, technical resources, training products, and information for anyone interested in developing applications on Apple platforms. Customers receive the quarterly APDA Tools Catalog featuring all current versions of Apple development tools and the most popular third-party development tools. Ordering is easy; there are no membership fees, and application forms are not required for most of our products. APDA offers convenient payment and shipping options, including site licensing.
To order products or to request a complimentary copy of the APDA Tools Catalog, contact
APDA
Apple Computer, Inc.
P.O. Box 319
Buffalo, NY 14207-0319Telephone 800-282-2732 (United States)
800-637-0029 (Canada)
716-871-6555 (International)
Fax 716-871-6511
AppleLink APDA
America Online APDA
CompuServe 76666,2405
Internet APDA@applelink.apple.com
If you provide commercial products and services, call 408-974-4897 for information on the developer support programs available from Apple.
For information on registering signatures, file types, and other technical information, contact
Macintosh Developer Technical Support
Apple Computer, Inc.
20525 Mariani Avenue, M/S 75-3T
Cupertino, CA 95014-6299
The Apple Event Registrar maintains the Apple Event Registry: Standard Suites and other information about the ongoing development of Apple event suites. For more information about Apple event suites, including those under development, send electronic mail to the AppleLink address REGISTRY.
Listing 1-0
Table 1-0
Introduction to Interapplication Communication
Contents
Overview of Interapplication Communication1-3
Sharing Data Among Applications1-6
Sending and Responding to Apple Events1-9
Standard Apple Events1-10
Handling Apple Events1-12
Supporting AppleScript and Other Scripting Languages1-13
Scriptable Applications1-16
Recordable Applications1-18
Applications That Manipulate and Execute Scripts1-19
Exchanging Message Blocks1-22
Introduction to Interapplication Communication
This chapter describes the interapplication communication (IAC) architecture for Macintosh computers, summarizes how your application can take advantage of it, and tells you where in this book to find the information you need to perform specific tasks.
The Apple Event Manager, Event Manager, and Program-to-Program Communications (PPC) Toolbox underlie all the IAC tasks your application can perform. This chapter introduces the Apple Event Manager and the Program-to-Program Communications Toolbox. For information about the Event Manager, see Inside Macintosh: Macintosh Toolbox Essentials. For definitions of the standard Apple events available for use by all applications, see the Apple Event Registry: Standard Suites.
The IAC architecture includes the Open Scripting Architecture (OSA). The OSA provides a mechanism that allows users to control multiple applications by means of scripts, or sets of instructions, written in a variety of scripting languages. Each scripting language has a corresponding scripting component that is managed by the Component Manager. When a user executes a script, the scripting component sends Apple events to one or more applications to perform the actions the script describes.
This chapter introduces the OSA and describes how to make your application scriptable, or capable of responding to Apple events sent to it by a scripting component.
For more information about using the Component Manager, see Inside Macintosh: More Macintosh Toolbox.
Overview of Interapplication Communication
The interapplication communication (IAC) architecture provides a standard and extensible mechanism for communication among Macintosh applications. The IAC architecture makes it possible for your application to
n provide automated copy and paste operations between your application and other applications
n be manipulated by means of scripts
n send and respond to Apple events
n send and respond to high-level events other than Apple events
n read and write blocks of data between applications
The chapter “Event Manager” in Inside Macintosh: Macintosh Toolbox Essentials describes how your application can use Event Manager routines to send and respond to high-level events. High-level events need not adhere to any specific protocol, so their interpretation is defined by each application that sends or receives them.
The most important requirement for high-level communication among all applications is a common vocabulary of events. To provide such a standard, Apple Computer, Inc., has defined a protocol called the Apple Event Interprocess Messaging Protocol (AEIMP). High-level events that conform to this protocol are called Apple events.
The vocabulary of publicly available Apple events is published in the Apple Event Registry: Standard Suites, which defines the standard Apple events that developers and Apple have worked out for use by all applications. To ensure that your application can communicate at a high level with other applications that support Apple events now and in the future, you should support the standard Apple events that are appropriate for your application.
Effective IAC requires close cooperation among applications at several levels. In addition to the format for high-level events and the standard vocabulary of Apple events, Apple has defined several other standards your application can use to communicate with other applications. These include standard methods for dealing with shared dynamic data, scripts, and low-level message blocks.
The IAC architecture comprises the following parts:
n The Edition Manager allows applications to automate copy and paste operations between applications, so that data can be shared dynamically.
n The Open Scripting Architecture (OSA) provides a standard mechanism, based on the Apple Event Manager, that allows users to control multiple applications by means of scripts written in a variety of scripting languages.
n The Apple Event Manager allows applications to send and respond to Apple events.
n The Event Manager allows applications to send and respond to high-level events other than Apple events.
n The Program-to-Program Communications (PPC) Toolbox allows applications to exchange blocks of data with each other by reading and writing low-level message blocks. It also provides a standard user interface that allows a user working in one application to select another application with which to exchange data.
Figure 1-1 shows the primary relationships among these parts. The managers and components toward the top of the figure rely on the managers beneath them. The Edition Manager uses the services of the Apple Event Manager to support dynamic data sharing. Scripting components manipulate and execute scripts with the aid of the Apple Event Manager. The Apple Event Manager in turn relies on the Event Manager to send Apple events as high-level events, and the Event Manager uses the services of the PPC Toolbox.
Figure 1-1 also shows the five principal means of communication provided by the IAC architecture. In addition to using the Edition Manager and scripting components to send Apple events on their behalf, applications can use the Apple Event Manager directly to send Apple events to other applications. All applications can use the Apple Event Manager to respond appropriately to Apple events, whether they are sent by the Edition Manager, a scripting component, or other applications. Applications can also use the Event Manager directly to send or receive high-level events other than Apple events, and the PPC Toolbox directly to send or receive blocks of data.
Figure 1-1 Principal methods of communication between applications
The five forms of IAC shown in Figure 1-1 can be summarized as follows:
n Sharing dynamic data. The Edition Manager allows users to copy data from one application’s document to another application’s document, updating information automatically when the data in the original document changes. The verbs publish and subscribe describe this form of dynamic data sharing, and the noun edition describes a copy of the data to be shared. Applications that support dynamic data sharing must implement the Create Publisher and Subscribe To menu commands. The Edition Manager provides the interface that allows applications to share editions.
You can let users publish and subscribe on a local volume or across a network. In general, users should be able to publish or subscribe to anything that they can copy or paste. “Sharing Data Among Applications,” which begins on page 1-6, describes how you can use the publish and subscribe features in your application.
n Scripting. The OSA includes the Apple Event Manager, the Apple events defined by the Apple Event Registry: Standard Suites, and the routines supported by scripting components, which applications can use via the Component Manager to execute scripts. Script-editing applications such as Script Editor (not shown in Figure 1-1) allow users to manipulate and execute scripts.
Each scripting language has a corresponding scripting component that can execute scripts written in that language. Scripting components typically implement a text-based scripting language based on Apple events. For example, the AppleScript component implements AppleScript, the standard user scripting language defined by Apple Computer, Inc. When the AppleScript component executes a script, it performs the actions described in the script, including sending Apple events to applications when necessary.
“Supporting AppleScript and Other Scripting Languages,” which begins on page 1-13, describes how the OSA makes it possible for your application to
n provide human-language equivalents to Apple event codes so that scripting components can send your application the appropriate Apple events during script execution
n allow users to record their actions in the form of a script
n manipulate and execute scripts
n Sending and responding to Apple events. Your application can send Apple events directly to other applications to request services or information or to provide information. To support AppleScript and most other scripting languages based on the OSA, your application must be able to respond to Apple events. “Sending and Responding to Apple Events,” which begins on page 1-9, describes how applications can send and respond to Apple events with the aid of the Apple Event Manager.
n Sending and responding to other high-level events. The Event Manager allows applications to support high-level events other than Apple events. See the chapter “Event Manager” in Inside Macintosh: Macintosh Toolbox Essentials for information about high-level events.
n Exchanging message blocks. The PPC Toolbox allows applications to exchange blocks of data with each other by reading and writing low-level message blocks. This method of communication is most useful for applications that are closely integrated, specifically designed to work together, or dependent on each other for information. It can also be used in code that is not event-based. See “Exchanging Message Blocks” on page 1-22 for a summary of the capabilities provided by the PPC Toolbox.
All forms of IAC are based on the premise that applications cooperate with each other. Both the application sending a high-level event or low-level message block and the application receiving it must agree on the protocol for communication. You can ensure effective high-level communication between your application and other Macintosh applications by supporting the standard Apple events defined in the Apple Event Registry: Standard Suites.
Sharing Data Among Applications
All Macintosh applications can use the Scrap Manager to share static data by allowing the user to copy and paste data between documents. Dynamic data sharing, or automated copy and paste operations between applications, extends this capability to dynamically changing data. The Edition Manager lets applications share dynamic data at the user’s request. You incorporate publish and subscribe capabilities in your application much as you incorporate copy and paste capabilities.
A user can publish data by selecting a portion of text, graphics, or other data in a document and choosing Create Publisher from the Edit menu. In response, your application saves the selected information in a separate file. This stored information is referred to as an edition. The user can subscribe to an edition by choosing Subscribe To from the Edit menu; when the user selects a file that contains an edition, your application includes the information from the edition in the current document. The information in an edition can be shared by many documents.
Figure 1-2 shows the principal relationships among the Edition Manager, the publishing application, the subscribing application, and the file that contains the edition. In addition to the relationships illustrated in the figure, the Edition Manager uses the Apple Event Manager to communicate with applications that are sharing dynamic data.
Figure 1-2 Sharing data with the aid of the Edition Manager
A publisher is a portion of a document that is made available to other documents through an edition. A subscriber is a portion of a document that reads the information from an edition.
Figure 1-3 shows a document containing a publisher, a file containing an edition, and a document containing a subscriber. The bottom fish in the Fishes of the World document is a publisher. The information from this publisher is made available to other documents through the Illustration edition. The Aquarium poster document contains a subscriber that gets its information from the Illustration edition. Note that when a user selects a publisher or subscriber within a document, your application should display a border surrounding the publisher or subscriber.
In general, when a user modifies the contents of a publisher and saves the document, your application should write the new data to the edition. The Edition Manager then uses the Apple Event Manager to inform all open applications with subscribers to the edition that it has been updated. These applications can then automatically update the subscribers in the documents.
Figure 1-3 A publisher, an edition, and a subscriber
For example, suppose the user changes the color of the fish in the Fishes of the World document shown in Figure 1-3, then saves the document. This automatically changes the Illustration edition, and the subscribing application can update the Aquarium poster document if that’s what the user wants to do.
Figure 1-4 shows how a user might create a poster from information contained in other documents.
Figure 1-4 Sharing dynamic data with other applications
Your application should save the new information in the edition whenever the user edits the publisher and saves the document that contains the publisher—unless the user has indicated that the information should be saved in the edition on request only. When the user saves new information in an edition, the Edition Manager replaces the previous contents.
When an edition is updated, the Edition Manager informs your application. Your application should then update any subscribers (unless the user has indicated that updates should be incorporated on request only).
For example, suppose a user opens a word-processing document called My Stocks that accesses information from an edition called Stock Report. The Stock Report edition might be updated twice a day by an online database. As the information in the edition changes, the My Stocks document can receive automatic updates with the latest information.
You can implement publish and subscribe capabilities in your application by using the routines provided by the Edition Manager and supporting the related Apple events. The chapter “Edition Manager” in this book provides sample code that shows how to add these features to your application. The chapter “Responding to Apple Events” in this book describes how to support the related Apple events.
Sending and Responding to Apple Events
An Apple event is a high-level event that conforms to the Apple Event Interprocess Messaging Protocol. The Apple Event Manager uses the Event Manager to send Apple events between applications on the same computer or between applications on remote computers.
Applications typically use Apple events to request services and information from other applications or to provide services and information in response to such requests. For example, any application can use the Get Data Apple event to request that your application locate and return a particular set of data, such as a table. If your application supports the Get Data event, it should be able to recognize the event and respond by locating the requested data and returning a copy of the data to the application that requested it.
Communication between two applications that support Apple events is initiated by a client application, which sends an Apple event to request a service or information. For example, a client application might request services such as printing specific files, checking the spelling of a list of words, or performing a numeric calculation; or it might request information, such as one customer’s address or a list of names and addresses of all customers living in Ohio. The application providing the service or the requested information is called a server application. The client and server applications can reside on the same local computer or on remote computers connected to a network.
Figure 1-5 shows the relationships among a client application, the Apple Event Manager, and a server application. The client application uses Apple Event Manager routines to create and send the Apple event, and the server application uses Apple Event Manager routines to interpret the Apple event and respond appropriately. If the client application so requests, the server application adds information to a reply Apple event that the Apple Event Manager returns to the client application.
Figure 1-5 Sending and responding to Apple events with the aid of the Apple Event Manager
If an Apple event is one of the standard events defined in the Apple Event Registry: Standard Suites, the client application can construct the event and the server application can interpret it according to the standard definition for that event. To ensure that your application can respond to Apple events sent by other applications, you should support the standard Apple events that are appropriate for your application.
Standard Apple Events
The current edition of Apple Event Registry: Standard Suites defines the standard suites of Apple events, which are groups of related events that are usually implemented together. The Apple Event Registrar maintains the Apple Event Registry: Standard Suites and other information about the ongoing development of Apple event suites.
The standard suites include the following:
n The Required suite consists of the four Apple events that the Finder sends to applications. These events are Open Application, Open Documents, Print Documents, and Quit Application. The Finder uses the required events as part of the mechanisms in System 7 and later versions for launching and terminating applications. To support System 7, your application must support the required Apple events as described in the chapter “Responding to Apple Events” in this book.
n The Core suite consists of the basic Apple events, including Get Data, Set Data, Move, Delete, and Save, that nearly all applications use to communicate. You should support the Apple events in the Core suite that make sense for your application.
n A functional-area suite consists of a group of Apple events that support a related functional area. Functional-area suites include the Text suite and the Database suite. You can decide which functional-area suites to support according to which features your application provides. For example, most word-processing applications should support the Text suite, and most database applications should support the Database suite.
You do not need to implement all Apple events at once. You should begin by supporting the required Apple events, then add support for the events sent by the Edition Manager, the core events, and the functional-area events as appropriate for your application.
If necessary, you can extend the definitions of the standard Apple events to suit specific capabilities of your application. You can also define your own custom Apple events. However, only those applications that choose to support your custom Apple events explicitly will be able to make use of them. If all applications communicated solely by means of custom Apple events, every application would have to support all other applications’ custom events. Instead of creating custom Apple events, try to use the standard Apple events and extend their definitions as necessary.
Apple events describe actions to be performed by the applications that receive them. In addition to a vocabulary of actions, or “verbs,” effective communication between applications requires a method of referring to windows, data (such as words or graphic elements), files, folders, volumes, zones, and other items on which actions can be performed. The Apple Event Manager provides a method for specifying structured names, or “noun phrases,” that applications can use to describe the objects on which Apple events act.
The Apple Event Registry: Standard Suites includes definitions for Apple event object classes, which are simply names for objects that can be acted upon by each kind of Apple event. Applications use these definitions and Apple Event Manager routines to create complex descriptions of almost any discrete item in another application or its documents. For example, an application could use Apple Event Manager routines and standard object class definitions to construct a Get Data event that requests “the most recent invoice to John Chapman in the Invoices database on the Archives server in the Accounting zone” and send the event to the appropriate application across the network.
An Apple event object is any item supported by an application, such as a word, paragraph, shape, or document, that can be described in an Apple event. In the example just given, the specified invoice, the Invoices database, the Archives server, and the Accounting zone are nested Apple event objects. Nearly any item that a user can differentiate and manipulate on a Macintosh computer can be described as an Apple event object of a specified object class nested within other Apple event objects. When handling an Apple event that includes such a description, an application must locate the specified Apple event object and perform the requested action on it.
Most of the standard Apple events defined in the Apple Event Registry: Standard Suites require your application to recognize specific Apple event object classes. Support for the standard Apple events, including Apple event object classes, allows your application to respond to requests for services or information from any other application or process.
Handling Apple Events
Figure 1-6 shows a common Apple event from the Core suite, the Set Data event. The SurfDB application is the client; it sends a Set Data event to the SurfCharter application. This event requests that SurfCharter use some new sales figures generated by SurfDB to update the data for the chart named “Summary of Sales” in the document named “Sales Chart.” The Apple event contains information that identifies an action—setting data—and a description of the Apple event object on which to perform the action—“the chart named Summary of Sales in the document named Sales Report.” The Apple event also includes the new data for the chart.
Figure 1-6 A Set Data event
To respond appropriately, the SurfCharter application in Figure 1-6 can use the Apple Event Manager to determine what kind of Apple event has been sent and pass the event to the appropriate Apple event handler. An Apple event handler is an application-defined function that extracts pertinent data from an Apple event, performs the requested action, and returns a result. In this case, the Set Data event handler must locate an Apple event object—that is, the specified chart in the specified document—and change the data displayed in the chart as requested.
The Apple Event Manager provides routines that a server application can use in its Apple event handlers to take apart an Apple event and examine its contents. The SurfCharter application in Figure 1-6 can interpret the contents of the Set Data Apple event according to the definition of that event in the Apple Event Registry: Standard Suites. The Set Data event handler uses both Apple Event Manager routines and the SurfCharter application’s own routines to locate the chart and make the requested change.
The Apple Event Manager also provides routines that a client application can use to construct and send an Apple event. However, the most important requirement for applications that support IAC is the ability to respond to Apple events, because this ability is essential for an application that users can control through scripts. The next section describes how you can use Apple events to support scripting in your application.
The chapter “Introduction to Apple Events” in this book provides an overview of Apple events and describes how you can use the Apple Event Manager to implement Apple events in your application. The chapters “Responding to Apple Events,” “Creating and Sending Apple Events,” “Resolving and Creating Object Specifier Records,” and “Recording Apple Events” provide detailed information about the Apple Event Manager.
Supporting AppleScript and Other Scripting Languages
A script is any collection of data that, when executed by the appropriate program, causes a corresponding action or series of actions. For example, some database, telecommunications, and page-layout applications allow users to automate repetitive or conditional tasks by means of scripts written in proprietary scripting languages. The HyperTalk® scripting language allows users to control the behavior of HyperCard® stacks. Macro programs can automate tasks at the level of mouse clicks and keystrokes.
The Open Scripting Architecture (OSA) provides a standard mechanism that allows users to control multiple applications with scripts written in a variety of scripting languages. Each scripting language has a corresponding scripting component. When a scripting component executes a script, it performs the actions described in the script, including sending Apple events to applications if necessary.
The OSA comprises the following parts:
n The Apple Event Manager allows applications to respond to Apple events sent by scripting components (see the previous section, “Sending and Responding to Apple Events”).
n The Apple Event Registry: Standard Suites defines the standard vocabulary of Apple events.
n The standard scripting component data structures, routines, and resources allow applications to interact with any scripting component.
n The AppleScript component implements the AppleScript scripting language.
The AppleScript component, which implements the AppleScript scripting language, is the implementation of the OSA provided by Apple Computer, Inc. Users can view a script written in the AppleScript scripting language in several different dialects, or versions of the AppleScript language that resemble specific human languages or programming languages.
Figure 1-7 shows the relationships among some of these parts. The client application in Figure 1-7 is Script Editor, an application provided by Apple Computer, Inc., that allows users to record, edit, and execute scripts. The client application could also be any other application that uses the standard scripting component routines to execute scripts. Script Editor uses the Component Manager to open a connection with the scripting component that created the script to be executed.
Figure 1-7 How a scripting component executes a script
Like sound resources, scripts can be stored in applications and documents as well as in distinct script files that can be manipulated from the Finder. Script Editor allows users to execute scripts stored in script files. Users can also execute special script files called script applications simply by opening them from the Finder.
During script execution, scripting components perform actions described in the script, using the Apple Event Manager to send Apple events when necessary. The server applications shown in Figure 1-7 use the Apple Event Manager to examine the contents of the Apple events they receive and to respond appropriately. A server application always responds to the same Apple event in the same way, regardless of whether the event is sent by a scripting component or directly by a client application.
You can take advantage of the OSA in three ways:
n You can make your application scriptable, or capable of responding to Apple events sent to it by a scripting component. An application is scriptable if it
n Responds to the appropriate standard Apple events. See the previous section, “Sending and Responding to Apple Events.”
n Provides an Apple event terminology extension ('aete') resource that describes which Apple events your application supports and the corresponding human-language terminology for use in scripts. The 'aete' resource allows scripting components to interpret scripts correctly and send the appropriate Apple events to your application during script execution.
By executing scripts, users of scriptable applications can perform almost any task that they would otherwise perform by choosing menu commands, typing, and so on. Users can also execute scripts to perform many tasks that might otherwise be difficult to accomplish, especially repetitive or conditional tasks that involve multiple applications.
n You can make your application recordable—that is, capable of sending Apple events to itself in response to user actions such as choosing a menu command or changing the contents of a document. After a user has turned on recording for a particular scripting component, the scripting component receives copies of all subsequent Apple events and records them in the form of a script.
n You can have your application manipulate and execute scripts with the aid of a scripting component. To do so, your application must
n use the Component Manager to open a connection with the appropriate component
n use the standard scripting component routines to record, edit, compile, save, load, or execute scripts when necessary
Users of applications that execute scripts can modify the applications’ behavior by editing the scripts. For example, a user of an invoice program might be able to write a script that checks and if necessary updates customer information in a separate database application each time the user posts an invoice.
The sections that follow describe these three kinds of scripting capabilities in more detail. The chapter “Introduction to Scripting” in this book provides an overview of the way scripting components work and how you can implement support for scripting in your application.
Scriptable Applications
If your application can respond to standard Apple events sent by other applications, it can also respond to the same Apple events sent by a scripting component. Before executing a script that controls your application, a scripting component must associate the human-language terms used in the script with specific Apple event codes supported by your application. Scriptable applications provide this information in an Apple event terminology extension ('aete') resource.
Because scripting components can obtain information from 'aete' resources about the nature of different applications’ support for Apple events, a single script can describe complex tasks performed cooperatively by several specialized applications. For example, a user can execute an AppleScript script to locate all records in a database with specific characteristics, update a series of charts based on those records, import the charts into a page-layout document, and send the document to a remote computer on the network via electronic mail.
When a user executes such a script, the AppleScript component attempts to perform the actions the script describes, including sending Apple events to various applications when necessary. To map human-language terms used in the script to the corresponding Apple events supported by each application, the AppleScript component looks up the terms in the applications’ 'aete' resources. Each human-language term specified by an application’s 'aete' resource has a corresponding Apple event code. After the AppleScript component has identified the Apple event codes for the terms used in a script, it can create and send the Apple events that perform the actions described in the script.
To respond appropriately to the Apple events sent to it by the AppleScript component, the database application in this example must be able to locate records with specific characteristics so that it can identify and return the requested data. The other applications involved must support Apple events that perform the other actions described in the script.
One line in such a script might be a statement like this:
copy Totals to chart "Summary of Sales" of document "Sales Chart"
In this statement, the word Totals is a variable that has been set earlier in the same script to the value of the new data generated by a database application. The statement causes the AppleScript component to send a Set Data event updating the chart named “Summary of Sales.” Figure 1-8 shows how the AppleScript component would execute this statement. (Figure 1-6 on page 1-12 shows a database application that sends a similar Set Data event directly.)
To interpret the terms in this script statement correctly, the AppleScript component must be able to look them up in the SurfCharter application’s 'aete' resource, which maps those terms to the corresponding codes for Apple events, object classes, and so on used by the Apple Event Manager. The AppleScript component can then create and send the Set Data event to SurfCharter.
When it receives the Set Data event, the SurfCharter application uses the Apple Event Manager to determine what kind of Apple event has been sent and to pass the event to SurfCharter’s handler for that event, which in turn locates the chart and changes its data as requested.
The chapter “Introduction to Scripting” in this book describes how the 'aete' resource works. The chapter “Apple Event Terminology Resources” describes how to define terminology for use by the AppleScript component and how to create an 'aete' resource.
Figure 1-8 A Set Data event sent during script execution
Recordable Applications
If you decide to make your application scriptable, you can also make it recordable, allowing users to record their actions in your application in the form of a script. Even users with little or no knowledge of a particular scripting language can record their actions in recordable applications in the form of a script. More knowledgeable users can record scripts and then edit or combine them as desired.
Applications generally have two parts: the code that implements the application’s user interface and the code that actually performs the work of the application when the user manipulates the interface. To make your application fully recordable, you should separate these two parts of your application, using Apple events to connect user actions with the work your application performs.
Any significant user action within a recordable application should generate Apple events that a scripting component can record as statements in a script. For example, when a user chooses New from the File menu, a recordable application sends itself a Create Element event, and the application’s handler for that event creates the new document. Implementing Apple events in this manner is called factoring your application. A factored application acts as both the client and the server application for the Apple events it sends to itself.
In general, a recordable application should generate Apple events for any user action that could be reversed by the Undo command. A recordable application can usually handle a greater variety of Apple events than it can record, since it must record the same action the same way every time even though Apple events might be able to trigger that action in several different ways.
A recordable event is any Apple event that any recordable application sends to itself while recording is turned on for the local computer (with the exception of events that the application indicates it does not want to be recorded). After a user turns on recording from the Script Editor application, the Apple Event Manager sends copies of all recordable events to Script Editor. A scripting component previously selected by the user handles each copied event for Script Editor by translating the event into the scripting component’s scripting language and recording the translation as part of a Script Editor script. When a scripting component executes a recorded script, it sends the corresponding Apple events to the applications in which they were recorded.
Figure 1-9 illustrates how Apple event recording works. The user performs a significant action (such as choosing New from the File menu), and the SurfCharter application sends itself an Apple event to perform the task associated with that action. If recording is turned on, the Apple Event Manager automatically sends a copy of each recordable Apple event to the application (for example, Script Editor) that initiated recording. The scripting component handles the copy of each recordable event by translating it and recording it as part of a script. To translate each Apple event correctly, the scripting component must first check what equivalent human-language terminology the SurfCharter application uses for that Apple event. The scripting component then records the equivalent statement in the script.
The chapter “Recording Apple Events” in this book describes the Apple Event Manager’s recording mechanism in more detail and explains how to use Apple events to factor your application.
Figure 1-9 Recording user actions in a factored application
Applications That Manipulate and Execute Scripts
Like sound resources, scripts can be stored either as separate files with their own icons in the Finder or within an application or its documents. Your application can store and execute scripts regardless of whether it is scriptable or recordable. If your application is scriptable, however, it can execute scripts that control its own behavior, thus acting as both the client application and the server application for the corresponding Apple events.
Your application can establish a connection with any scripting component that is registered with the Component Manager on the same computer. Each scripting component can manipulate and execute scripts written in the corresponding scripting language (or, as in the case of AppleScript, one of the scripting language’s dialects) when your application calls the standard scripting component routines.
You can use the standard scripting component routines to
n get a handle to a script so you can save the script in a preferences file, in the data fork of a document, or as a separate script file
n manipulate scripts associated with any part of your application or its documents, including both Apple event objects and other objects defined by the application
n let users record and edit scripts
n compile and execute scripts
Figure 1-10 shows how an application might execute a script that controls its own behavior. The appropriate user action handler executes the script in response to a user action, which can be almost anything: choosing a menu command, clicking a button, tabbing from one table cell to another, and so on. The script might consist of a single statement that describes some default action, such as saving or printing, or a series of statements that describe a series of tasks, such as setting default preferences or styles. Figure 1-10 shows a script that corresponds to a single Apple event, but the script could just as easily correspond to a whole series of Apple events. If your application allows users to modify such a script, they can modify the behavior of your application to suit their needs.
Figure 1-10 Controlling an application’s own behavior by executing a script
Your application can associate a script with any Apple event object or application-defined object and execute the script when that object is manipulated in some way. The script can describe actions to be taken by your application, as in
Figure 1-10, or actions to be taken by several applications. For example, a user of a word-processing application might attach a script to a specific word so that the application executes the script whenever that word is double-clicked. Such a script could trigger Apple events that look up and display related information from a separate document, run a QuickTime movie, perform a calculation, play a voice annotation, and so on.
Figure 1-11 shows one way that a script can be used to control two or more applications. When a user chooses the Post Invoice command in the accounting application, the user action handler for that menu command executes a default script for posting an invoice. That script might describe actions such as saving the invoice, updating the sales journal, and so on. The scripting component sends Apple events to the accounting application to perform these actions.
Figure 1-11 Posting an invoice and updating a database by executing a script
The accounting application also allows users to open the default invoice-posting script in Script Editor and modify it so that additional actions are performed when it is executed. For example, as shown in Figure 1-11, the script could instruct the SurfDB application to update a database of customer information in addition to performing the default posting actions. In this case, the scripting component sends Apple events to both the accounting application and SurfDB to carry out all the actions described by the script.
There is no limit to the actions such a script can describe. In addition to sending the Apple events shown in Figure 1-11, the invoice-posting script could be used to trigger Apple events that cause other applications to perform a credit check, send the invoice to the customer by electronic mail, forward inventory information to a remote server on the network, and so on.
The chapter “Scripting Components” in this book describes how your application can use the standard scripting component routines to manipulate and execute its own scripts and allow users to modify those scripts.
Exchanging Message Blocks
You should be able to meet most of your application’s IAC needs by using the Apple Event Manager or the Event Manager. However, if you need low-level control or services not provided by the Apple Event Manager or the Event Manager, you can use the PPC Toolbox. The PPC Toolbox lets you send large amounts of data to other applications located on the same computer or across a network. The PPC Toolbox can also be used by pieces of code that are not event-driven. The PPC Toolbox is usually called by the Operating System; device drivers, desk accessories, or other code modules can also use it.
You cannot use the PPC Toolbox to send data between applications unless both your application and the application you’re communicating with are open at the same time. To initiate communication, one program opens a port and requests a session with another program. The target application must also open a port and accept the request. Once a session is established, the two programs can read and write low-level message blocks.
The PPC Toolbox also provides a standard user interface that allows a user working in one application to select another application with which to exchange data, whether the communication is achieved by means of Apple events, other high-level events, or message blocks.
The chapter “Program-to-Program Communications Toolbox” in this book describes how programs can exchange low-level message blocks.
Listing 2-0
Table 2-0
Edition Manager
Contents
Introduction to Publishers, Subscribers, and Editions2-4
About the Edition Manager2-12
Using the Edition Manager2-12
Receiving Apple Events From the Edition Manager2-13
Creating the Section Record and Alias Record2-15
Saving a Document Containing Sections2-19
Opening and Closing a Document Containing Sections2-22
Reading and Writing a Section2-24
Formats in an Edition2-24
Opening an Edition2-26
Format Marks2-27
Reading and Writing Edition Data2-27
Closing an Edition2-28
Creating a Publisher2-29
Creating the Edition Container2-32
Opening an Edition Container to Write Data2-35
Creating a Subscriber2-37
Opening an Edition Container to Read Data2-41
Choosing Which Edition Format to Read2-41
Using Publisher and Subscriber Options2-43
Publishing a New Edition While Saving or Manually2-47
Subscribing to an Edition Automatically or Manually2-48
Canceling Sections Within Documents2-48
Locating a Publisher Through a Subscriber2-49
Renaming a Document Containing Sections2-50
Displaying Publisher and Subscriber Borders2-50
Text Borders2-54
Spreadsheet Borders2-55
Object-Oriented Graphics Borders2-56
Bitmapped Graphics Borders2-57
Duplicating Publishers and Subscribers2-58
Modifying a Subscriber2-59
Relocating an Edition2-60
Customizing Dialog Boxes2-60
Subscribing to Non-Edition Files2-62
Getting the Current Edition Opener2-63
Setting an Edition Opener2-63
Calling an Edition Opener2-64
Opening and Closing Editions2-68
Listing Files That Can Be Subscribed To2-68
Reading From and Writing to Files2-68
Calling a Format I/O Function2-68
Edition Manager Reference2-71
Data Structures2-71
The Edition Container Record2-71
The Section Record2-72
Edition Manager Routines2-73
Initializing the Edition Manager2-74
Creating and Registering a Section2-74
Creating and Deleting an Edition Container2-79
Setting and Getting a Format Mark2-81
Reading in Edition Data2-83
Writing out Edition Data2-86
Closing an Edition After Reading or Writing2-88
Displaying Dialog Boxes2-90
Locating a Publisher and Edition From a Subscriber2-98
Edition Container Formats2-101
Reading and Writing Non-Edition Files2-102
Application-Defined Routines2-105
Summary of the Edition Manager2-106
Pascal Summary2-106
Constants2-106
Data Types2-108
Edition Manager Routines2-111
Application-Defined Routines2-113
C Summary2-114
Constants2-114
Data Types2-116
Edition Manager Routines2-119
Application-Defined Routines2-122
Result Codes2-122
Edition Manager
This chapter describes how you can use the Edition Manager to allow your users to share and automatically update data from numerous documents and applications.
The Edition Manager is available only in System 7 or later. It can be used by many different applications located on a single disk or throughout a network of Macintosh computers. To test for the existence of the Edition Manager, use the Gestalt function, described in Inside Macintosh: Operating System Utilities.
Read the information in this chapter if you want your application’s documents to share and automatically update data, or if you want to share and automatically update data with documents created by other applications that support the Edition Manager.
For example, a user might want to capture sales figures and totals from within a spreadsheet and then include this information in a word-processing document that summarizes sales for a given month. The Edition Manager establishes a connection between these two documents. When a user modifies the spreadsheet, the information in the word-processing document can be automatically updated to contain the latest changes. To accomplish this, both the spreadsheet application and the word-processing application must support the features of the Edition Manager.
To use this chapter, you should be familiar with sending and receiving high-level events, described in the chapter “Event Manager” in Inside Macintosh: Macintosh Toolbox Essentials. Your application must also support Apple events to receive Apple events from the Edition Manager. See the following chapters in this book for detailed information on Apple events.
The Edition Manager provides you with the ability to
n capture data within a document and integrate it into another document
n modify information in a document and automatically update any document that shares its data
n share information between applications on the same computer or across a network of Macintosh computers
Building the capabilities of the Edition Manager into your program is similar to building cut-and-paste features into your program. Text, graphics, spreadsheet cells, database reports—any data that you can select, you can make accessible to other applications that support the Edition Manager. The next section provides an overview of the main elements of the Edition Manager. Following sections discuss how to implement these features in your application.
This chapter also describes an advanced feature that allows applications to share data directly from a file.
Introduction to Publishers, Subscribers, and Editions
A section is a portion of a document that shares its contents with other documents. The Edition Manager supports two types of sections: publishers and subscribers. A publisher is a section within a document that makes its data available to other documents or applications. A subscriber is a section within a document that obtains its data from other documents or applications.
Your application writes a copy of the data in each publisher to a separate file called an edition container. The actual data that is written to the edition container is referred to as the edition. Your application obtains the data for each subscriber by reading data from the edition container. Note that throughout this chapter, the term edition refers to the edition container and the data it contains.
You publish data when you want to make it available to other documents and applications. When data is published, it is stored in an edition container. You subscribe to data that a publisher makes available by reading an edition from its container.
Note
Section and edition container are programmatic terms. You should not use them in your application or your documentation. Use publishers, subscribers, and editions. You should also refrain from using other terms such as publication or subscription to describe the dynamic sharing of information provided by the Edition Manager. Use the terms publish and subscribe to describe the Edition Manager features.u
Each edition has an icon that is visible from the Finder. Figure 2-1 shows the default edition icon.
Figure 2-1 The default edition icon
The name that the user specifies for the edition is located next to the edition icon. For information on providing icons for the editions created by your application, see the chapter “Finder Interface” in Inside Macintosh: Macintosh Toolbox Essentials. Figure 2-2 illustrates a document containing a single publisher, its corresponding edition, and a subscriber to the edition in another document.
Figure 2-2
A publisher, an edition, and a subscriber
Note that the publisher and subscriber borders illustrated in Figure 2-2 may appear slightly different from the borders you see on the screen. Figure 2-6 on page 2-9 shows the publisher and subscriber borders as they appear onscreen.
Data always flows in one direction, from publisher to edition to subscriber. Documents that contain publishers and subscribers do not have to be open at the same time to share data. Whenever the user saves a document that contains a publisher, the edition changes to reflect the current data from the publisher. All subscribers update their contents from the edition. Any number of subscribers can subscribe to a single edition.
To create a publisher within a document, a user selects an area of the document to share and chooses Create Publisher from the Edit menu (see Figure 2-7 on page 2-10). Figure 2-3 shows the dialog box that your application should display when the user chooses Create Publisher.
Figure 2-3 The publisher dialog box
Your application provides a thumbnail sketch of the edition data, which the Edition Manager displays in the preview area of the publisher dialog box. Your preview of the edition in this dialog box should provide a visual cue about the type of information that the user has selected to publish.
A preview area also appears in the subscriber dialog box (see Figure 2-4). This preview, too, should provide a visual cue about the type of information the edition contains. For example, it should allow users to distinguish between text information and spreadsheet arrays.
The publisher dialog box uses the extended interface of the standard file dialog box that accompanies System 7. The user navigates through the contents of the disk using the mouse or keyboard.
A user can modify a publisher within a document just like any other portion of a document. As a default, each time a user saves a document containing a publisher, your application should automatically write the publisher’s data to the edition. You also need to provide the user with the choice of sending new publisher data to an edition manually (that is, only at the user’s specific request). You should provide these options by using the publisher options dialog box described later in “Using Publisher and Subscriber Options” beginning on page 2-43.
For example, one user may choose to update an edition automatically each time a document is saved. This update mode is useful for a user who creates a publisher within a spreadsheet application that records stock information. Each time the user updates the stock information and saves the spreadsheet, a new edition automatically becomes available to subscribers.
Another user may choose to update an edition only upon request. This update mode might be useful for a user who creates a publisher within a word-processing application for a quarterly sales report. The user incrementally updates the sales report throughout the entire quarter but does not want this information to be available to subscribers until the end of the quarter. Only at the end of each quarter does the user specifically request to update the edition and make it available to any subscribers.
To create a subscriber within a document, the user places the insertion point and chooses Subscribe To from the Edit menu. Figure 2-4 shows the dialog box that your application should display when the user chooses Subscribe To.
Figure 2-4
The subscriber dialog box
The subscriber dialog box also uses the extended interface of the standard file dialog box introduced with System 7. Initially, the dialog box should highlight the name of the last edition published or subscribed to. This allows a user to create a publisher and immediately subscribe to its edition.
A subscriber receives its data from a single edition. By default, your application should automatically update a document containing a subscriber whenever a new edition is available. You also need to provide the user with the choice of receiving the latest edition manually (that is, only when the user specifically requests it). You can provide these options by using the subscriber options dialog box described later in “Using Publisher and Subscriber Options” beginning on page 2-43.
For example, one user may choose to receive new editions automatically as they become available. This update mode is useful for a user who subscribes to information from an edition that consists of daily sales figures. This user automatically acquires each version of the sales information as it becomes available.
Another user may choose to receive a new edition only upon request. This update mode is useful for a user who creates a subscriber to an edition that consists of graphics data (such as a company logo). The user may require only periodic versions of the logo and not need frequent updates. In this case, your application should update the subscriber with a new edition only when the user specifically requests it.
A user can select, cut, copy, or paste an entire subscriber. Although the contents of the subscriber as a whole can be modified, a user cannot edit portions of a subscriber. For example, a user can underline or italicize the entire subscriber text but cannot delete a sentence or rotate a single graphic object. This restriction protects the user from losing changes to a subscriber when a new edition arrives. Remember that, as a default, new editions should automatically update a subscriber. Any changes that a user made to the subscriber text would have to be reapplied by the user when the new edition arrives. See “Modifying a Subscriber” on page 2-59 for further information.
A single document can contain any number or combination of publishers and subscribers. Figure 2-5 shows an example of a document that contains two publishers and one subscriber (and their corresponding editions). Remember that data always flows in one direction, from publisher to edition to subscriber. The “Concert flyer” document contains a publisher that is subscribed to by the “Benefit concert” document. The “Concert flyer” document also subscribes to a portion of the “Pianos & palm trees” document. In addition, the “Concert flyer” document as a whole is subscribed to by the “Sample flyer” document.
Figure 2-5 A document and its corresponding editions
You should distinguish each selected publisher and subscriber within a document with a border. Display a publisher border as three pixels wide with 50 percent gray lines, and display a subscriber border as three pixels wide with 75 percent gray lines. A rectangle of one white pixel should separate the data from the border itself. Borders should be drawn outside the contents of publishers and subscribers so that data is not obscured. See
Figure 2-6 for an illustration of the borders as they appear onscreen. See “Displaying Publisher and Subscriber Borders” on page 2-50 for detailed information on how to implement borders for specific applications.
Figure 2-6 shows a document containing a publisher and a document containing a subscriber, with borders displayed for each.
Borders for publishers and subscribers should behave like the borders of 'PICT' graphics within a word-processing document. Your application should display a border whenever the user clicks within the content area of a publisher or a subscriber. Your application should hide the border whenever the user clicks outside the content area. See “Displaying Publisher and Subscriber Borders” on page 2-50 for detailed information on how to implement borders for specific applications.
Figure 2-6 Publisher and subscriber borders
You also need to support the standard Edition Manager menu commands in the Edit menu. These menu items include
n Create Publisher…
n Subscribe To…
n Publisher/Subscriber Options…
n Show/Hide Borders (optional)
n Stop All Editions (optional)
Use a divider to separate the Edition Manager menu commands from the standard Edit menu commands Cut, Copy, and Paste. Figure 2-7 shows the standard Edition Manager menu commands.
Figure 2-7 Edition Manager commands in the Edit menu
The Subscriber Options menu command should toggle with the Publisher Options menu command. When a user selects a subscriber and then accesses the menu bar, your application should adjust its menus so that the Subscriber Options menu command appears in the Edit menu. When a user selects a publisher and then accesses the menu bar, your application should adjust its menus so that the Publisher Options menu command appears in the Edit menu. In addition, you may support a Show Borders menu command that toggles with Hide Borders to display or hide all publishers and subscriber borders within documents. You may also support a Stop All Editions menu command to provide a method for temporarily suspending all update activity in a document. When the user chooses this command, you should place a checkmark next to it. You should also stop all publishers from sending data to editions and all subscribers from receiving new editions. When the user chooses this command again, remove the checkmark and update any subscribers that are set up to receive new editions automatically.
If you find that you need all of the available space in the Edit menu for your application’s commands, you may create a hierarchical menu for the Edition Manager menu commands. If you choose to implement this structure, you should allow users to access the Edition Manager menu commands through a Publishing menu command in the Edit menu. Because this menu structure is not as accessible to users, you should implement it only if you have no other alternative.
Figure 2-8 shows the Edition Manager menu commands in a hierarchical menu structure.
Figure 2-8 Edition Manager commands under the Publishing menu command
For each publisher or subscriber within an open document, you must have a section record and an alias record. The section record contains a time stamp that records the version of the data that resides in the section. The section record also identifies the section as either a publisher or subscriber, and it establishes a unique identity for each publisher or subscriber. The section record does not contain the data within the section. The alias record is a reference to the edition container from the document that contains the corresponding publisher or subscriber section.
There are special options associated with publishers and subscribers within documents. Your application can use the publisher and subscriber options dialog boxes provided by the Edition Manager to make these choices available to the user. For example, a user can select Open Publisher within the subscriber options dialog box to access the document containing the publisher. Your application can also allow a user to cancel subscribers or publishers within documents, specify when to update an edition from a publisher, or specify when to update a subscriber with a new edition. These options are described in “Using Publisher and Subscriber Options” beginning on page 2-43.
About the Edition Manager
The next section discusses how to save, open, read, and write a document that shares data. In addition, it describes how to
n make data accessible to other applications
n integrate data into numerous documents
n set update options
n implement borders
n modify shared data
n customize dialog boxes
n subscribe to data in non-edition files
Using the Edition Manager
This section describes how your application can
n receive Apple events from the Edition Manager
n set up a section record and alias record for open documents containing sections
n save a document that contains sections
n open a document that contains sections
n read and write sections
n create a publisher within a document, create its edition container, and write data to it
n create a subscriber within a document and read its data from an edition
To begin, you must determine whether the Edition Manager is available on the system by using the Gestalt function with the gestaltEditionMgrAttr ('edtn') selector. If the response parameter returns 1 in the bit defined by the gestaltEditionMgrPresent constant (bit 0), the Edition Manager is present.
If the Edition Manager is present, load it into memory using the InitEditionPack function. This function determines whether the machine has enough space in the system heap for the Edition Manager to operate.
err := InitEditionPack;
If the InitEditionPack function returns noErr, you have enough space to load the package. If you do not have enough space, the application can either terminate itself or continue with the Edition Manager functionality disabled.
Receiving Apple Events From the Edition Manager
Applications that use the Edition Manager must support Apple events. This requires that your application support the required Open Documents event and Apple events sent by the Edition Manager. See the chapter “Introduction to Apple Events” in this book for general information on Apple events.
Apple events sent by the Edition Manager arrive as high-level events. The EventRecord data type defines the event record.
TYPE EventRecord =
RECORD
what: Integer; {kHighLevelEvent}
message: LongInt; {'sect'}
when: LongInt;
where: Point; {'read', 'writ', 'cncl', 'scrl'}
modifiers: Integer;
END;
The Edition Manager can send these Apple events with the event class and event ID as shown here:
n Section Read events ('sect' 'read')
n Section Write events ('sect' 'writ')
n Section Cancel events ('sect' 'cncl')
n Section Scroll events ('sect' 'scrl')
Each time your application creates a publisher or a subscriber, the Edition Manager registers its section. When an edition is updated, the Edition Manager scans its list to locate registered subscribers. For each registered subscriber that is set up to receive updated editions automatically, your application receives a Section Read event.
If the Edition Manager discovers that an edition file is missing while registering a publisher, it creates a new edition file and sends the publisher a Section Write event.
When you receive a Section Cancel event, you need to cancel the specified section. Note that the current Edition Manager does not send you Section Cancel events, but you do need to provide a handler for future expansion.
If the user selects a subscriber within a document and then selects Open Publisher in the subscriber options dialog box, the publishing application receives the Open Documents event and opens the document containing the publisher. The publishing application also receives a Section Scroll event. Scroll to the location of the publisher, display this section on the user’s screen, and turn on its border.
See “Opening and Closing a Document Containing Sections” beginning on page 2-22 for detailed information on registering and unregistering a section and writing data to an edition. See “Using Publisher and Subscriber Options” beginning on page 2-43 for information on publisher and subscriber options.
After receiving an Apple event sent by the Edition Manager, use the Apple Event Manager to extract the section handle. In addition, you must also call the IsRegisteredSection function to determine whether the section is registered. It is possible (because of a race condition) to receive an event for a section that you recently disposed of or unregistered. One way to ensure that an event corresponds to a valid section is to call the IsRegisteredSection function after you receive an event.
err := IsRegisteredSection (sectionH);
Listing 2-1 illustrates how to use the Apple Event Manager and install an event handler to handle Section Read events. You can write similar code for Section Write events, Section Scroll events, and Section Cancel events.
Listing 2-1 Accepting Section Read events and verifying if a section is registered
{this routine reads in subscriber data and updates its display}
FUNCTION DoSectionRead(subscriber: SectionHandle): OSErr;
BEGIN
{your code here}
END; {DoSectionRead}
{this is part of your Apple event–handling code}
FUNCTION MyGetSectionHandleFromEvent(theAppleEvent: AppleEvent;
VAR sectionH: SectionHandle)
: OSErr;
VAR
ignoreType: DescType;
ignoreSize: Size;
BEGIN
{parse section handle out of message buffer}
MyGetSectionHandleFromEvent
:= AEGetParamPtr( theAppleEvent, {event to parse}
keyDirectObject, {look for direct }
{ object}
typeSectionH, {want a SectionHandle}
ignoreType, {ignore type it could }
{ get}
@sectionH, {put SectionHandle }
{ here}
SizeOf(sectionH), {size of storage for }
{ SectionHandle}
ignoreSize); {ignore storage it }
{ used}
END; {MyGetSectionHandleFromEvent}
In addition to the Section Read, Section Write, Section Cancel, and Section Scroll events, your application can also respond to the Create Publisher event. For more information on this event, as well as additional information on how to handle Apple events, see the chapter “Responding to Apple Events” in this book.
Creating the Section Record and Alias Record
Your application is responsible for creating a section record and an alias record for each publisher and subscriber section within an open document.
The section record identifies each section as a publisher or subscriber and provides identification for each section. The section record does not contain the data within the section; it describes the attributes of the section. Your application must provide its own method for associating the data within a section with its section record. Your application is also responsible for saving the data in the section.
The alias field of the section record contains a handle to its alias record. The alias record is a reference to the edition container from the document that contains the publisher or subscriber section. You should be familiar with the Alias Manager’s conventions for creating alias records and identifying files, folders, and volumes to locate files that have been moved, copied, or restored from backup. For information on the Alias Manager, see Inside Macintosh: Files.
When a user saves a document, your application should store all section records and alias records in the document’s resource fork. Corresponding section records and alias records should have the same resource ID.
Figure 2-9 shows a document containing a publisher and subscriber, and the corresponding section records and alias records.
Figure 2-9 A document with a publisher and subscriber and its resource fork
A section record contains information to identify the data contained within a section as a publisher or a subscriber, a time stamp to record the last modification of the section, and unique identification for each section. The SectionRecord data type defines the section record.
TYPE SectionRecord =
RECORD
version: SignedByte; {always 1 in 7.0}
kind: SectionType; {publisher or subscriber}
mode: UpdateMode; {automatic or manual}
mdDate: TimeStamp; {last change in document}
sectionID: LongInt; {application-specific, }
{ unique per document}
refCon: LongInt; {application-specific}
alias: AliasHandle; {handle to alias record}
{The following fields are private and are set up by the }
{ RegisterSection function described later within this }
{ chapter. Do not modify the private fields.}
subPart: LongInt; {private}
nextSection: SectionHandle; {private, do not use as a }
{ linked list}
controlBlock: Handle; {may be used for comparison }
{ only}
refNum: EditionRefNum; {private}
END;
Field descriptions
version Indicates the version of the section record, currently $01.
kind Defines the section type as either publisher or subscriber with the stPublisher or stSubscriber constant.
mode Indicates if editions are updated automatically or manually.
mdDate Indicates which version (modification date) of the section’s contents is contained within the publisher or subscriber. The mdDate field is set to 0 when you create a new subscriber section and to the current time when you create a new publisher. Be sure to update this field each time publisher data is modified. The section’s modification date is compared to the edition’s modification date to determine whether the section and the edition contain the same data. The section modification date is displayed in the publisher and subscriber options dialog boxes. See “Closing an Edition” on page 2-28 for detailed information.
sectionID Provides a unique number for each section within a document. A simple way to implement this is to create a counter for each document that is saved to disk with the document. The counter should start at 1. The section ID is currently used as a tie breaker in the GoToPublisherSection function when there are multiple publishers to the same edition in a single document. The section ID should not be 0 or –1. See “Duplicating Publishers and Subscribers” on page 2-58 for information on multiple publishers.
refCon Reference constant available for application-specific use.
alias Contains a handle to the alias record for a particular section within a document.
Whenever the user creates a publisher or subscriber, call the NewSection function to create the section record and the alias record.
The NewSection function creates a new section record (either publisher or subscriber), indicates whether editions are updated automatically or manually, sets the modification date, and creates an alias record from the document containing the section to the edition container.
You can set the sectionDocument parameter to NIL if the current document has never been saved. Use the AssociateSection function to update the alias record of a registered section when the user names or renames a document by choosing Save As from the File menu. If you are creating a subscriber with the initialMode parameter set to receive new editions automatically, your application receives a Section Read event each time a new edition becomes available for this subscriber.
If an error is encountered, the NewSection function returns NIL in the sectionH parameter. Otherwise, NewSection returns a handle to the allocated section record in the sectionH parameter.
Set the initialMode parameter to the update mode for each subscriber and publisher created. You can specify the update mode using these constants:
CONST sumAutomatic = 0; {subscriber receives new }
{ editions automatically}
sumManual = 1; {subscriber receives new }
{ editions manually}
pumOnSave = 0; {publisher sends new }
{ editions on save}
pumManual = 1; {publisher does not send }
{ new editions until user }
{ request}
See “Using Publisher and Subscriber Options” beginning on page 2-43 for detailed information on update modes for publishers and subscribers. See Listing 2-4 beginning on page 2-33 for code that uses the NewSection function to create a publisher. See Listing 2-6 on page 2-40 for code that uses NewSection to create a subscriber.
Saving a Document Containing Sections
When saving a document that contains sections, you should write out each section record as a resource of type 'sect' and write out each alias record as a resource of type 'alis' with the same ID as the section record. See the chapter “Resource Manager” in Inside Macintosh: More Macintosh Toolbox for detailed information on resources.
If a user closes a document that contains newly created publishers without attempting to save its contents, you should display an alert box similar to the one shown in Figure 2-10.
Figure 2-10 The new publisher alert box
If you keep the section records and alias records for each publisher and subscriber as resources, you can use the ChangedResource or WriteResource function. If you detach the section records and alias records from each section, you need to clone the handles and use the AddResource function. See the chapter “Resource Manager” in Inside Macintosh: More Macintosh Toolbox for detailed information on the ChangedResource, WriteResource, and AddResource functions.
Use the PBExchangeFiles function to ensure that the file ID remains the same each time you save a document that contains sections. Saving a file typically involves creating a new file (with a temporary name), writing data to it, closing it, and then deleting the original file that you are replacing. You rename the temporary file with the original filename, which leads to a new file ID. The PBExchangeFiles function swaps the contents of the two files (even if they are open) by getting both catalog entries and swapping the allocation pointers. If the files are open, the file control block (FCB) is updated so that the reference numbers still access the same contents (under a new name). See Inside Macintosh: Files for detailed information on the PBExchangeFiles function.
Listing 2-2 illustrates how to save a file that contains sections. If the contents of a publisher have changed since the last save, the application-defined procedure MySaveDocument writes the publisher’s data to its edition. It then writes out to the saved document the section records and alias records of all publishers and subscribers. MySaveDocument calls another application-defined routine, MyGetSectionAliasPair, to return a handle and resource ID to a section. As described earlier, you should write out the eligible section records and alias records as resources to allow for future compatibility. There are several different techniques for saving or adding resources; this listing illustrates one technique. The section handles are still valid after using the AddResource function because this listing illustrates just saving, not closing, the file.
Before you write out sections, you need to see if any publisher sections share the same control block. Publishers that share the same control block share the same edition.
If a user creates an identical copy of a file by choosing Save As from the File menu and does not make any changes to this new file, you simply use the AssociateSection function to indicate to the Edition Manager which document a section is located in.
Opening and Closing a Document Containing Sections
When opening a document that contains sections, your application should use the GetResource function to get the section record and the alias record for each publisher and subscriber. Set the alias field of the section record to be the handle to the alias. See the chapter “Resource Manager” in Inside Macintosh: More Macintosh Toolbox for detailed information on the GetResource function.
You also need to register each section using the RegisterSection function. The RegisterSection function informs the Edition Manager that a section exists.
err := RegisterSection(sectionDocument, sectionH,
aliasWasUpdated);
The RegisterSection function adds the section record to the Edition Manager’s list of registered sections. This function assumes that the alias field of each section record is a handle to the alias record. The alias record is a reference to the edition container from the section’s document. If the RegisterSection function successfully locates the edition container for a particular section, the section is registered through a shared control block. The control block is a private field in the section record.
If the RegisterSection function cannot find the edition container for a particular subscriber, RegisterSection returns the containerNotFoundWrn result code. If the RegisterSection function cannot find the edition container for a particular publisher, RegisterSection creates an empty edition container for the publisher in the last place the edition was located. The Edition Manager sends your application a Section Write event for that section.
When a user attempts to open a document that contains multiple publishers to the same edition, you should warn the user by displaying an alert box (see “Duplicating Publishers and Subscribers” on page 2-58).
When a user opens a document that contains a subscriber (with an update mode set to automatic), receives a new edition, and then closes the document without making any changes to the file, you should update the document and simply allow the user to close it. You do not need to prompt the user to save changes to the file.
When closing a document that contains sections, you must unregister each section (using the UnRegisterSection function) and dispose of each corresponding section record and alias record.
err := UnRegisterSection(sectionH);
The UnRegisterSection function removes the section record from the list of registered sections and unlinks itself from the shared control block.
Listing 2-3 illustrates how to open an existing file that contains sections. As described earlier, you should retrieve the section and alias resources, connect the pair through the alias field of the section record, and register the section with the Edition Manager. There are many different techniques for retrieving resources; this listing shows one technique. If an alias was out of date and was updated by the Alias Manager during the resolve, the Edition Manager sets the aliasWasUpdated parameter of the RegisterSection function to TRUE. This means that you should save the document. Additionally, your application must maintain its own list of registered sections for each open document that contains sections. You use this list to write out new editions for updated publishers within a document.
Listing 2-3 Opening a document containing sections
Your application writes publisher data to an edition. New publisher data replaces the previous contents of the edition, making the previous edition information irretrievable. Your application reads data from an edition for each subscriber within a document.
The following sections describe how to
n use different formats to write to or read from an edition
n open an edition to initiate writing or reading
n set a format mark
n write to or read from an edition
n close an edition after successfully writing or reading data
Formats in an Edition
You can write data to an edition in several different formats. These formats are the same as scrap format types. Scrap format types are indicated by a four-character tag.
Typically, when a user copies data, you identify the scrap format types and then write the data to the scrap. With the Edition Manager, when a user decides to publish data, you identify the format types and then write the data to an edition. You can write multiple formats of the same data.
For an edition, you should write your preferred formats first. In general, to write data to an edition, your application should use either 'TEXT' format or 'PICT' format. This allows your application to share data with most other applications. To subscribe to an edition, your application should be able to read both 'TEXT' and 'PICT' files. In addition, your application can write any other private formats that you want to support.
Scrap format types are described in the chapter “Scrap Manager” in Inside Macintosh: More Macintosh Toolbox.
A few special formats are defined as constants.
CONST kPublisherDocAliasFormat = 'alis'; {alias record from the }
{ edition to publisher}
kPreviewFormat = 'prvw'; {'PICT' thumbnail }
{ sketch}
kFormatListFormat = 'fmts'; {lists all available }
{ formats}
The kPublisherDocAliasFormat ('alis') format is written by the Edition Manager. It is an alias record from the edition to the publisher’s document. Appended to the end of the alias is the section ID of the publisher, which the Edition Manager uses to distinguish between multiple publishers to a single edition. You should discourage users from making multiple copies of the same publisher. See “Duplicating Publishers and Subscribers” on page 2-58 for detailed information.
In addition to writing a publisher’s data to an edition in the 'TEXT' format or 'PICT' format, your application can also write data to an edition in the kPreviewFormat ('prvw') format. If you provide a 'prvw' format in an edition, the Edition Manager uses it to display a preview of the edition data in the preview area of the subscriber dialog box. The 'prvw' format has the same format as a 'PICT' file. To draw a preview in the 'prvw' format, the Edition Manager calls DrawPicture with a rectangle of 120 by 120 pixels. (See Inside Macintosh: Imaging for more information about DrawPicture.) Your application should provide data in a 'prvw' format so that the data displays well in a rectangle of this size. Your application can also use this preview to display subscriber data within a document (to save space).
If your application does not provide a preview in the 'prvw' format for an edition, the Edition Manager attempts to provide a preview by using the edition’s 'PICT' format. To draw a preview in the 'PICT' format, the Edition Manager examines the picture’s bounding rectangle and calls DrawPicture with a rectangle that scales the picture proportionally and centers it in a 120-by-12-pixel area.
The kFormatListFormat ('fmts') format is a virtual format that is read but never written. It is a list of all the formats and their lengths. Applications can use this format in place of the EditionHasFormat function (described in “Choosing Which Edition Format to Read” on page 2-41), which provides a procedural interface to determine which formats are available.
If your application can read two or more of the available formats, use 'fmts' to determine the priority of these formats for a particular edition. The order of 'fmts' reflects the order in which the formats were written.
The FormatsAvailable data type defines a record for the 'fmts' format.
TYPE FormatsAvailable = ARRAY[0..0] OF
RECORD
theType: FormatType; {format type for an edition}
theLength: LongInt; {length of edition format }
{ type}
END;
For example, an edition container may have a format type 'TEXT' of length 100, and a format type 'styl' of length 32. A subscriber to this edition can open it and then read the format type 'fmts' to list all available formats. In this example, it returns 16 bytes: 'TEXT' $00000064 'styl' $00000020.
Opening an Edition
For a publisher, use the OpenNewEdition function to initiate the writing of data to an edition. (Note that the edition container must already exist before you initiate writing; see “Creating the Edition Container” beginning on page 2-32.)
The publisherSectionH parameter is the publisher section that you are writing to the edition. The fdCreator parameter is the Finder creator type of the new edition. (The edition container file already has a creator type; you can specify the same creator type or establish a new creator type for the edition.)
The publisherSectionDocument parameter specifies the document that contains the publisher. This parameter is used to create an alias from the edition to the publisher’s document. If you pass NIL for publisherSectionDocument, an alias is not made in the edition file. The refNum parameter returns the reference number for the edition.
For a subscriber, use the OpenEdition function to initiate the reading of data from
an edition.
err := OpenEdition(subscriberSectionH, refNum);
The subscriberSectionH parameter is a handle to the section record for a given section. The refNum parameter returns the reference number for the edition.
The user may rename or move the edition in the Finder. Before writing to or reading data from an edition, the Edition Manager verifies the name of the edition. This process is referred to as synching or synchronization. Synching ensures that the Edition Manager’s existing edition names correspond to the Finder’s existing edition names by updating the control block.
Format Marks
Each format has its own mark. The mark indicates the next position of a read or write operation. Initially, a mark automatically defaults to 0. After reading or writing data, the format mark is set past the last position written to or read from. The mark is similar to the File Manager’s current read or write position marker for a data fork. Any time that an edition is open (after calling the OpenEdition or the OpenNewEdition function), any of the marks for each format can be queried or set.
To set the current mark for a section format to a new location, use the SetEditionFormatMark function.
The Edition Manager allows you to read or write data a few bytes at a time (as with a data fork of a Macintosh file) instead of in one block (as with the Scrap Manager). You can read sequentially by setting the mark to 0 and repeatedly calling read, or you can jump to a specific offset by setting the mark there. The Edition Manager also adds the capability to stream multiple formats by keeping a separate mark for each format. This allows you to write a few bytes of one format and then write a few bytes of another format, and so forth.
Once you have opened the edition container for a particular publisher, you can begin writing data to the edition. Use the WriteEdition function to write publisher data to an edition.
The WriteEdition function writes the specified format (beginning at the current mark for that format type) from the buffer pointed to by the buffPtr parameter up to buffLen bytes.
After you open the edition container for a subscriber and determine which formats to read, use the ReadEdition function to read edition data.
The ReadEdition function reads the data with the specified format (whichFormat) from the edition into the buffer. The ReadEdition function begins reading at the current mark for that format and continues to read up to buffLen bytes. The actual number of bytes read is returned in the buffLen parameter. Once the buffLen parameter returns a value smaller than the value you have specified, there is no additional data to read, and the ReadEdition function returns a noErr result code.
Note
The Translation Manager (if it is available) attempts implicit translation under certain circumstances. For instance, it does so when your application attempts to read from an edition a format type that is not in the edition. In this case, the Translation Manager attempts to translate the data into the requested format. For more information, see the chapter “Translation Manager” in Inside Macintosh: More Macintosh Toolbox.u
Closing an Edition
When you are done writing to or reading data from an edition, call the CloseEdition function.
err := CloseEdition(whichEdition, successful);
Each time a user edits a publisher within a document, you must update the modification date in the section record (even if the data is not yet written). When the update mode is set to Manually, the user can compare the modification dates for a publisher and its edition in the publisher options dialog box. One modification date indicates when the publisher last wrote data to the edition, and the other modification date indicates when the publisher section was last edited.
If the successful parameter for a publisher is TRUE, the CloseEdition function makes the newly written data available to subscribers and sets the modification date in the mdDate field of the edition to correspond to the modification date of the publisher’s section record. If the two dates differ, the Edition Manager sends a Section Read event to all current subscribers.
If the successful parameter for a subscriber is TRUE, the CloseEdition function sets the modification date of the subscriber’s section record to correspond to the modification date of the edition.
If you cannot successfully read from or write data to an edition, set the successful parameter to FALSE. For a publisher, data is not written to the edition, but it should still be saved with the document that contains the section. When the document is next saved, data can then be written to the edition. See “Closing an Edition After Reading or Writing” on page 2-88 for additional information on the CloseEdition function.
Creating a Publisher
You need to support a Create Publisher menu command in the Edit menu. When a user selects a portion of a document and chooses Create Publisher from this menu, you should display the publisher dialog box on the user’s screen. The Create Publisher menu command should remain dimmed until the user selects a portion of a document.
Use the NewPublisherDialog function to display the publisher dialog box on the user’s screen. This function is similar to the CustomPutFile procedure described in the chapter “Standard File Package” in Inside Macintosh: Files.
err := NewPublisherDialog(reply);
The dialog box contains space for a preview (a thumbnail sketch) of the edition and a space for the user to type the name of the edition in which to write the publisher data. Figure 2-11 illustrates a sample publisher dialog box.
Figure 2-11 A sample publisher dialog box
The NewPublisherDialog function displays the preview (provided by your application), displays a text box with the default name of the edition (provided by your application), and handles all user input until the user clicks
Publish or Cancel.
You pass a new publisher reply record as a parameter to the NewPublisherDialog function.
TYPE NewPublisherReply =
RECORD
canceled: Boolean; {user clicked Cancel}
replacing: Boolean; {user chose existing }
{ filename for an edition}
usePart: Boolean; {always FALSE in version 7.0}
preview: Handle; {handle to 'prvw', 'PICT', }
{ 'TEXT', or 'snd ' data}
previewFormat: {type of preview}
FormatType;
container: EditionContainerSpec; {initially, default name }
{ and location of edition; }
{ on return, edition name & }
{ location chosen by the }
{ user to publish data to}
END;
You fill in the usePart, preview, previewFormat, and container fields of the new publisher reply record.
Always set the usePart field to FALSE. The preview field should contain either NIL or the data to display in the preview. The previewFormat field should contain 'PICT', 'TEXT', 'snd ', or 'prvw'.
Set the container field to be the default name and folder for the edition. The default name should reflect the data contained in the publisher. For example, if a user publishes a bar chart of sales information entitled “sales data,” then the default name for the edition could also be “sales data.” Otherwise, you should use the document name followed by a hyphen (-) and a number to establish uniqueness. For example, your default name could be “January Totals - 3.”
If the document has not been saved, the default name should be “untitled edition <n>” where n is a number to establish uniqueness. The default folder should be the same as the edition for the last publisher created in the same document. If this is the first publisher in the document, the default folder should be the same folder that the document is in.
The canceled field of the new publisher reply record indicates whether the user clicked Cancel. The replacing field indicates whether the user chose to replace an existing edition file. If replacing returns FALSE, call the CreateEditionContainerFile function to create an edition file.
The container field is of data type EditionContainerSpec.
TYPE EditionContainerSpec =
RECORD
theFile: FSSpec; {record that identifies the }
{ file to contain edition data}
theFileScript: ScriptCode; {script code of filename}
thePart: LongInt; {which part of file, }
{ always kPartsNotUsed}
thePartName: Str31; {not used in version 7.0}
thePartScript: ScriptCode; {not used in version 7.0}
END;
The field theFile is a file system specification record, a data structure of type FSSpec. You identify the edition using a volume reference number, directory ID, and filename. When specifying an edition, follow the standard conventions described in Inside Macintosh: Files.
After filling in the fields of the new publisher reply record, pass it as a parameter to the NewPublisherDialog function, which displays the publisher dialog box.
err := NewPublisherDialog(reply);
After displaying the publisher dialog box, use the CreateEditionContainerFile function to create the edition container, and then use the NewSection function to create the section record and the alias record. See the next section, “Creating the Edition Container,” and “Creating the Section Record and Alias Record” on page 2-15 for detailed information.
The following code segment illustrates how your application might respond to the user choosing the Create Publisher menu item. In this case, the code sets up the preview for the edition, sets the default name for the edition container, and calls an application-defined function (DoNewPublisher, shown in Listing 2-4 on page 2-33) to display the publisher dialog box on the user’s screen. An application might call the DoNewPublisher function in response to the user’s choosing Create Publisher from the Edit menu or in response to handling the Create Publisher event. The chapter “Responding to Apple Events” in this book gives an example of a handler for the Create Publisher event.
VAR
thisDocument: MyDocumentInfoPtr;
promptForDialog: Boolean;
preview: Handle;
previewFormat: FormatType;
defaultLocation: EditionContainerSpec;
myErr: OSErr;
BEGIN
{Get a preview to show the user. The MyGetPreviewForSelection }
This function creates an edition container. The edition container is empty (that is, it does not contain any formats) at this time.
To associate an icon with the edition container, create the appropriate entries for the icon in your application’s bundle. See the chapter “Finder Interface” in Inside Macintosh: Macintosh Toolbox Essentials for additional information. Depending on the contents of the edition, the file type will be 'edtp' (for graphics), 'edtt' (for text), or 'edts' (for sound).
After creating the edition container, use the NewSection function to create the section record and alias record for the section.
Listing 2-4 illustrates how to create a publisher. The DoNewPublisher function shown in the listing is a function provided by an application. Note that an application might call the DoNewPublisher function in response to the user’s choosing the Create Publisher command or in response to the Create Publisher event. The chapter “Responding to Apple Events” in this book gives an example of a handler for the Create Publisher event.
The parameters to the DoNewPublisher function include a pointer to information about the document, a Boolean value that indicates if the function should display the new publisher dialog box, the preview for the edition, the preview format, and an edition container.
The function displays the publisher dialog box if requested, letting the user accept or change the name of the edition and the location where the edition should reside. Use the CreateEditionContainerFile function to create the edition with the given name and location. Use the NewSection function to create a new section for the publisher.
After the section is created, you must write out the edition data. Be sure to add the newly created section to your list of sections for this document. There are several different techniques for creating publishers and unique IDs; this listing displays one technique.
After creating the edition container and creating a new section record, the DoNewPublisher function calls another application-defined routine, DoWriteEdition, to open the edition and write data to it.
Listing 2-4 Creating a publisher
FUNCTION DoNewPublisher(thisDocument: MyDocumentInfoPtr;
promptForDialog: Boolean;
preview: Handle;
previewFormat: FormatType;
editionSpec: EditionContainerSpec)
: OSErr;
VAR
getLastErr, dialogErr: OSErr;
createErr, sectionErr: OSErr;
resID: Integer;
thisSectionH: SectionHandle;
reply: NewPublisherReply;
BEGIN
{set up info for new publisher reply record}
reply.replacing := FALSE;
reply.usePart := FALSE;
reply.preview := preview;
reply.previewFormat := previewFormat;
reply.container := editionSpec;
IF promptForDialog THEN
BEGIN {user interaction is allowed}
{display dialog box and let user select}
dialogErr := NewPublisherDialog(reply);
{dispose of preview data handle}
DisposeHandle(reply.preview);
IF dialogErr <> noErr THEN MyErrHandler(dialogErr);
IF reply.canceled THEN
BEGIN {do nothing if user canceled}
DoNewPublisher := userCanceledErr;
EXIT(DoNewPublisher);
END;
END; {of promptForDialog}
IF NOT reply.replacing THEN
BEGIN
{if user isn't replacing an existing file, create a new one}
{Remember that the section and alias records need to be }
{ saved as resources when the user saves the document.}
{set the function result appropriately}
DoNewPublisher := MyGetLastError;
END;
Opening an Edition Container to Write Data
Several routines are required to write (publish) data from a publisher to an edition container. (For information on creating an edition container, see the previous section.) Before writing data to an edition, you must use the OpenNewEdition function. This function should be used only for a publisher within a document. Use this function to initiate the writing of data to an edition.
A user may try to save a document containing a publisher that is unable to write its data to an edition—because another publisher (that shares the same edition) is writing, another subscriber (that shares the same edition) is reading, or a publisher located on another computer is registered to the section. In such a case, you may decide to refrain from writing to the edition so that the user does not have to wait. You should also refrain from displaying an error to the user. The contents of the publisher are saved to disk with the document. The next time that the user saves the document, you can write the publisher data to the edition. You should display an alert box to discourage users from making multiple copies of the same publisher and pasting them in the same or other documents (see “Duplicating Publishers and Subscribers” on page 2-58).
If a user clicks Send Edition Now within the publisher options dialog box (to write publisher data to an edition manually), and the publisher is unable to write its data to its edition (for any of the reasons outlined above), you should display an error message.
After you are finished writing data to an edition, use the CloseEdition function to close the edition.
Listing 2-5 illustrates how to write data to an edition. For an existing edition container, you must open the edition, write each format using the WriteEdition function, and close the edition using the CloseEdition function. This listing shows how to write text only. If the edition is written successfully, subscribers receive Section Read events.
{There were problems writing; simply close the edition. }
{ When successful = FALSE, the edition data <> section }
{ data. Note: this isn't fatal or bad; it just means }
{ that the data wasn't written and no Section Read events }
{ will be generated.}
closeErr := CloseEdition(eRefNum, FALSE);
END
ELSE
BEGIN
{The write was successful; now close the edition. }
{ When successful = TRUE, the edition data = section data.}
{ This edition is now available to any subscribers. }
{ Section Read events will be sent to current subscribers.}
closeErr := CloseEdition(eRefNum, TRUE);
END;
END;
Creating a Subscriber
You need to create a Subscribe To menu command in the Edit menu. When a user chooses Subscribe To from this menu, your application should display the subscriber dialog box on the user’s screen.
Use the NewSubscriberDialog function to display the subscriber dialog box on the user’s screen. This function is similar to the CustomGetFile procedure described in the chapter “Standard File Package” in Inside Macintosh: Files.
To create a subscriber, you must get information from the user, such as the name of the edition being subscribed to. The dialog box displays a listing of all available editions and allows the user to see a preview (thumbnail sketch) of the edition selected. Figure 2-12 shows a sample subscriber dialog box.
Figure 2-12 A sample subscriber dialog box
The subscriber dialog box allows the user to choose an edition to subscribe to. The NewSubscriberDialog function handles all user interaction until a user clicks Subscribe or Cancel. When a user selects an edition container, the Edition Manager accesses the preview for the edition container (if it is available) and displays it.
You pass a new subscriber reply record as a parameter to the NewSubscriberDialog function.
The canceled field returns a Boolean value of TRUE if the user clicked Cancel. To indicate which edition format types (text, graphics, or sound) your application can read, you set the formatsMask field to one or more of these constants:
CONST kPICTformatMask = 1; {can subscribe to 'PICT'}
kTEXTformatMask = 2; {can subscribe to 'TEXT'}
ksndFormatMask = 4; {can subscribe to 'snd '}
To support a combination of formats, add the constants together. For example, a formatsMask of 3 displays both graphics and text edition format types in the subscriber dialog box.
The container field is of data type EditionContainerSpec. You must initialize the container field with the default edition volume reference number, directory ID, filename, and part. To do so, use the GetLastEditionContainerUsed function to obtain the name of the last edition displayed in the dialog box.
err := GetLastEditionContainerUsed(container);
This function returns the last edition container for which a new section was created using the NewSection function. If there is no last edition, or if the edition was deleted, GetLastEditionContainerUsed still returns the correct volume reference number and directory ID to use, but leaves the filename blank and returns the fnfErr result code.
The container field is of data type EditionContainerSpec.
TYPE EditionContainerSpec =
RECORD
theFile: FSSpec; {file containing edition }
{ data}
theFileScript: ScriptCode; {script code of filename}
thePart: LongInt; {which part of file, }
{ always kPartsNotUsed}
thePartName: Str31; {reserved}
thePartScript: ScriptCode; {reserved}
END;
The field theFile is of type FSSpec. See Inside Macintosh: Files for further information on file system specification records.
After filling in the fields of the new subscriber reply record, pass it as a parameter to the NewSubscriberDialog function, which displays the subscriber dialog box.
err := NewSubscriberDialog(reply);
After displaying the subscriber dialog box, call the NewSection function to create the section record and the alias record. See “Creating the Section Record and Alias Record” beginning on page 2-15 for detailed information.
If the subscriber is set up to receive new editions automatically (not manually), the Edition Manager sends your application a Section Read event. Whenever your application receives a Section Read event, it should read the contents of the edition into the subscriber.
Listing 2-6 illustrates how to create a subscriber. As described earlier, you must set up and display the subscriber dialog box to allow the user to subscribe to any of the available editions. After your application creates a subscriber, your application receives a Section Read event to read in the data being subscribed to. Be sure to add the newly created section to your list of sections for this file. There are many different techniques for creating subscribers and unique IDs; this listing displays one technique.
{Remember that you will receive a Section Read event to read }
{ in the edition that you just subscribed to because the }
{ initial mode is set to sumAutomatic.}
{Remember that the section and alias records need to be saved }
{ as resources when the user saves the document.}
END;
Opening an Edition Container to Read Data
Before reading data from an edition, you must use the OpenEdition function. Your application should only use this function for a subscriber. Use this function to initiate the reading of data from an edition.
err := OpenEdition(subscriberSectionH, refNum);
As a precaution, you should retain the old data until the user can no longer undo. This allows you to undo changes if the user requests it.
Your application can supply a procedure such as DoReadEdition to read in data from the edition to a subscriber. When your application opens a document containing a subscriber that is set up to receive new editions automatically, the Edition Manager sends you a Section Read event if the edition has been updated. The Section Read event supplies the handle to the section that requires updating. Listing 2-7, shown in the next section, provides an example of reading data from an edition.
Choosing Which Edition Format to Read
After your application opens the edition container for a subscriber, it can look in the edition for formats that it understands. To accomplish this, use the EditionHasFormat function.
The EditionHasFormat function returns the noTypeErr result code if a requested format is not available. If the requested format is available, this function returns the noErr result code, and the formatSize parameter contains the size of the data in the specified format or kFormatLengthUnknown (–1), which signifies that the size is unknown.
Note
The Translation Manager (if it is available) attempts implicit translation under certain circumstances. For instance, it does so when your application attempts to read from an edition a format type that is not in the edition. In this case, the Translation Manager attempts to translate the data into the requested format. For more information, see the chapter “Translation Manager” in Inside Macintosh: More Macintosh Toolbox.u
After your application opens the edition container and determines which formats it wants to read, call the ReadEdition function to read in the edition data. See “Reading and Writing Edition Data” on page 2-27 for detailed information.
After you have completed writing the edition data into the subscriber section, call the CloseEdition function to close the edition. See “Closing an Edition” on page 2-28 for detailed information.
Listing 2-7 illustrates how to read data from an edition. As described earlier, you must open the edition, determine which formats to read, use the ReadEdition function to read in data, and then use the CloseEdition function to close the edition. This listing shows how to read only text.
{The read was successful; now close the edition. When }
{ successful = TRUE, the section data = edition data.}
closeErr := CloseEdition(eRefNum, TRUE);
EXIT(DoReadEdition);
END;
END; {of EditionHasFormat}
{'TEXT' format wasn't found or read error; just close }
{ the edition. FALSE tells the Edition Manager that your }
{ application did not get the latest edition.}
closeErr := CloseEdition(eRefNum, FALSE);
END;
Using Publisher and Subscriber Options
You can allow users to set several special options associated with publishers and subscribers. To set these preferences, users change settings in two dialog boxes provided by the Edition Manager: publisher options and subscriber options. To make these dialog boxes available to the user, provide a command in the Edit menu that toggles between Publisher Options (when the user has selected a publisher within a document) and Subscriber Options (when a user has selected a subscriber within a document).
When a user chooses one of these menu commands, you need to display the appropriate dialog box. Use the SectionOptionsDialog function to display the publisher options or subscriber options dialog box on the user’s screen.
err := SectionOptionsDialog(reply);
Each dialog box contains information regarding the section and its edition. Figure 2-13 shows the publisher options dialog box with the update mode set to On Save.
Figure 2-13 The publisher options dialog box with update mode set to On Save
Figure 2-14 shows the publisher options dialog box with the update mode set to Manually.
Figure 2-14 The publisher options dialog box with update mode set to Manually
As a shortcut for the user, you should display the publisher options dialog box when the user double-clicks a publisher section in a document.
Figure 2-15 shows the subscriber options dialog box with the update mode set to Automatically.
Figure 2-15 The subscriber options dialog box with update mode set to Automatically
Figure 2-16 shows the subscriber options dialog box with the update mode set to Manually.
Figure 2-16 The subscriber options dialog box with update mode set to Manually
As a shortcut for the user, you should display the subscriber options dialog box when the user double-clicks a subscriber section in a document.
You pass a section options reply record as a parameter to the SectionOptionsDialog function.
TYPE SectionOptionsReply =
RECORD
canceled: Boolean; {user clicked Cancel}
changed: Boolean; {changed section record}
sectionH: SectionHandle; {handle to the specified }
{ section record}
action: ResType; {action codes}
END;
Set the sectionH parameter to the handle to the section record for the section the user selected.
Upon return of the SectionOptionsDialog function, the canceled and changed fields are set. If the canceled field is set to TRUE, the user clicked Cancel. Otherwise, this field is set to FALSE. If the changed field is set to TRUE, the section record is changed. For example, the user may have changed the update mode.
The SectionOptionsDialog function returns in the action parameter the code for one of five user actions. The function dismisses the publisher and subscriber options dialog boxes after the user clicks a button.
n Action code is 'read' for a click of the Get Edition Now button.
n Action code is 'writ' for a click of the Send Edition Now button.
n Action code is 'goto' for a click of the Open Publisher button.
n Action code is 'cncl' for a click of the Cancel Publisher or Cancel Subscriber button.
n Action code is ' ' ($20202020) for a click of the OK button.
Listing 2-8 shows an example of how your application can respond to the action codes received from the section options reply record. You can use several different techniques for this purpose; this listing shows one technique.
BEGIN {User selected Cancel Publisher or Cancel Subscriber }
{ button. Call the UnRegisterSection function and dispose }
{ of the section record and alias record.}
EXIT(DoOptionsDialog);
END;
END;
The following sections describe the features of the publisher and subscriber options dialog boxes.
Publishing a New Edition While Saving or Manually
By default, your application should write publisher data to an edition each time the user saves the document and the contents of the publisher differ from the latest edition. In the publisher options dialog box, the user can choose to write new data to an edition each time the document is saved (by clicking On Save) or only upon the user’s specific request (by clicking Manually).
When the update mode is set to manual, a user must click the Send Edition Now button in the publisher options dialog box to write publisher data to an edition. When a user clicks this button, the section options reply record contains the action code 'writ'. In this case, you should write out the new edition. Writing to an edition manually is useful when a user tends to save a document numerous times while revising it.
Each time the user saves the document, check the update mode of the publisher section. If the publisher section sends its data to an edition when the document is saved, check whether the publisher data has changed since it was last written to the edition. If so, write the publisher’s data to the new edition.
In addition, you may also support a Stop All Editions menu command to provide a method for temporarily suspending all update activity. See “Introduction to Publishers, Subscribers, and Editions” beginning on page 2-4 for additional information.
Subscribing to an Edition Automatically or Manually
By default, your application should subscribe to an edition each time new edition data becomes available. In the subscriber options dialog box, the user can choose to read new data from an edition as the data is available (by clicking Automatically) or only upon the user’s specific request (by clicking Manually).
When the update mode is set to manual, the user must click the Get Edition Now button in the subscriber options dialog box to receive new editions. When a user clicks this button, the section options reply record contains the action code 'read'. In this case, you should read in the new edition. See “Opening an Edition Container to Read Data” beginning on page 2-41 for detailed information.
When the update mode is set to automatic, your application receives a Section Read event each time a new edition becomes available. In response, you should read the new edition data beginning with the OpenEdition function.
Your application does not receive Section Read events for subscribers that receive new editions manually.
You may also support a Stop All Editions menu command to provide a method for temporarily suspending all update activity. See “Introduction to Publishers, Subscribers, and Editions” beginning on page 2-4 for additional information.
Canceling Sections Within Documents
The option of canceling publishers and subscribers is available to the user through the Cancel Publisher and Cancel Subscriber buttons in the corresponding options dialog boxes. When the user clicks one of these buttons, the action code of the section options reply record is 'cncl'. See “Relocating an Edition” on page 2-60 for additional information on canceling a section.
When a user cancels a section (either a publisher or subscriber) and then saves the document, or when a user closes an untitled document (which contains newly created sections) without saving it, you must unregister each corresponding section record and alias record using the UnRegisterSection function. In addition, you should also delete the section record and alias record using the DisposeHandle procedure. See Inside Macintosh: Memory for additional information on the DisposeHandle procedure.
When a user cancels a publisher section and then saves the document, or when a user closes an untitled document (which contains newly created publishers) without saving it, you must also delete any corresponding edition containers (in addition to deleting section records and alias records).
Do not delete an edition container file, section record, or alias record until the user saves the document; the user may decide to undo changes before saving the document.
To locate the appropriate edition container to be deleted (before you use the UnRegisterSection function), use the GetEditionInfo function.
err := GetEditionInfo(sectionH, editionInfo);
The editionInfo parameter is a record of data type EditionInfoRecord.
TYPE EditionInfoRecord =
RECORD
crDate: TimeStamp; {date edition container }
{ was created}
mdDate: TimeStamp; {date of last change}
fdCreator: OSType; {file creator}
fdType: OSType; {file type}
container: EditionContainerSpec; {the edition}
END;
The GetEditionInfo function returns the edition container as part of the edition information.
The crDate field contains the creation date of the edition. The mdDate field contains the modification date of the edition.
The fdType and the fdCreator fields are the type and creator of the edition file. The container field includes a volume reference number, directory ID, filename, script, and part number for the edition.
To remove the edition container, use the DeleteEditionContainerFile function.
err := DeleteEditionContainerFile(editionFile);
Locating a Publisher Through a Subscriber
The user can locate a publisher from a subscriber within a document by clicking the Open Publisher button in the subscriber options dialog box. As a shortcut, Apple suggests that you also allow the user to locate a publisher by selecting a subscriber in a document and pressing Option–double-click.
When the action code of the SectionOptionsReply record is 'goto', use the GoToPublisherSection function.
err := GoToPublisherSection(container);
The GoToPublisherSection function locates the correct document by resolving the alias in the edition, and it launches the document’s application if necessary (the Edition Manager sends an Open Documents event). The Edition Manager then sends the publishing application a Section Scroll event. If the document containing the requested publisher is located on the same computer as its subscriber, the document opens and scrolls to the location of the publisher. If the document containing the requested publisher is located on a shared volume (using file sharing), the document opens and scrolls to the location of the publisher only if the user has privileges to open the document from the Finder.
You need to provide the GoToPublisherSection function with the edition container. To accomplish this, use the GetEditionInfo function. See the previous section, “Canceling Sections Within Documents,” for information on the GetEditionInfo function.
Renaming a Document Containing Sections
If a user renames a document that contains sections by choosing Save As from the File menu, or if a user pastes a portion of a document that contains a section into another document, use the AssociateSection function.
Use the AssociateSection function to update the alias record of a registered section.
The AssociateSection function internally calls the UpdateAlias function. It is also possible to update the alias record using the Alias Manager (see the chapter “Alias Manager” in Inside Macintosh: Files for additional information).
Displaying Publisher and Subscriber Borders
Each publisher and subscriber within a document should have a border that appears when a user selects the contents of these sections. You should display a publisher border as three pixels wide with 50 percent gray lines and a subscriber border as three pixels wide with 75 percent gray lines. Separate the contents of the section from the border itself with one pixel of white space. To create your borders, you should use patterns, not colors. Depending on the user’s monitor type, colors may not be distinguishable.
In general, borders for publishers and subscribers should behave like the borders of 'PICT' graphics in a word-processing document. A border should appear when the user clicks the content area of a publisher or a subscriber and disappear when
the user clicks outside the content area of a section. You can also make all publisher
and subscriber borders appear or disappear by implementing an optional
Show/Hide Borders menu command.
Figure 2-17 displays the Edition Manager Show/Hide Borders menu command in the Edit menu.
Figure 2-17 Edit menu with Show/Hide Borders menu command
Depending on your application, you may choose to include resize handles or similar components in your borders. See “Object-Oriented Graphics Borders” on page 2-56 for an example of resize handles.
Whenever a user selects a portion of a publisher or sets the insertion point within a publisher, you should display the border as 50 percent gray. A user can copy the contents of a publisher or subscriber without copying the section itself by selecting the data, copying, and then pasting the data in a new location. A user can cut and paste a selection that contains an entire publisher or subscriber, but you should discourage users from making multiple copies of a publisher. See “Duplicating Publishers and Subscribers” on page 2-58 for detailed information.
When the user modifies a publisher, your application should grow or shrink its border to accommodate the new dimension of the section.
You should display only one publisher border within a document at a time. If a cursor is inserted within a publisher that is contained within a larger publisher, you should display only the smaller, internal publisher border. If it is absolutely necessary to display all section borders within a document at the same time, you can create a Show/Hide Borders menu item.
You do not need to provide support for publishers contained within other publishers. If you do not, you should dim the Create Publisher menu command (to indicate that it is not selectable) when a user attempts to create a publisher within an existing publisher.
Figure 2-18 shows the recommended border behavior for publishers. The top window shows a publisher with its borders displayed. The middle window shows how the borders look when a user selects some of the contents of a section. The bottom window shows how the borders look when a user selects data within a document that includes a publisher section.
Figure 2-18 Publisher borders
Figure 2-19 shows the recommended border behavior for subscribers. The top window shows a subscriber with its borders displayed. The middle window shows how the borders look when a user selects the contents of a section. The bottom window shows how the borders look when a user selects data within a document that includes a subscriber section.
Figure 2-19 Subscriber borders
If a user tries to select only a portion of a subscriber, you should highlight the entire contents of the subscriber. A user cannot edit the data in a subscriber. See “Modifying a Subscriber” on page 2-59 for detailed information.
If a user cancels a section using the publisher or subscriber options dialog box, your application should leave the contents of the section within the document, but you should be sure to remove the borders from this data, as it is no longer considered a section.
Generally, the appearance and function of publisher and subscriber borders should be the same across different applications. The following sections entitled “Text Borders,” “Spreadsheet Borders,” “Object-Oriented Graphics Borders,” and “Bitmapped Graphics Borders” describe specialized features for publisher and subscriber borders in word-processing, spreadsheet, or graphics applications.
Text Borders
In word-processing documents, a publisher may contain other publishers. However, one publisher should not overlap another publisher. You should display only one publisher border at a time. If an insertion point is placed within a publisher that is encompassed by another larger publisher, you should display only the smaller internal publisher border.
In exceptional cases, it may be necessary to display more than one publisher or subscriber border at a time. For example, a publisher may consist of a paragraph that includes a marker for a footnote. The data contained within the footnote should also be considered part of the publisher. When a user selects the paragraph, you should simultaneously display a border around the footnote.
The border of a publisher that contains text should be located between characters within the text. The insertion point, when placed on such a boundary, should gravitate toward the publisher. That is, a click in front (to the left) of a publisher border should place the cursor inside the publisher, so that subsequent typing goes inside the publisher. Clicking at the end (to the right) of a publisher border should also place the cursor inside the publisher.
Whenever two separate borders are adjacent, the boundary click should go in between them. This is also true for a border that is next to other nontextual aspects of a document, such as 'PICT' graphics or page breaks.
When a user removes information from a publisher that contains text data, you should resize the border so that it becomes smaller. When a user adds information to the publisher, you should enlarge the border to accommodate the new text. The insertion point should remain within the publisher.
If a user highlights the entire contents of a publisher and then chooses Cut from the Edit menu, you should not delete the publisher border within the document. The user may intend to delete the existing publisher data and replace it with new data, or the user may want to move the entire publisher and its data to a new location. Figure 2-20 shows
this state.
Figure 2-20 A publisher with contents removed
You should leave the cursor inside the small publisher border for further typing. If the user inserts the cursor in a new location (instead of typing data inside the existing border), you need to remove the empty publisher border from the document to allow the user to move the publisher. This effectively deletes the publisher from the document. If the user pastes the publisher that is currently held in the scrap, you should re-create its border. If the user cuts or copies other data from the document before pasting the publisher from the scrap, the publisher should be removed from the scrap.
Spreadsheet Borders
Borders around spreadsheet data or other data in arrays should look and behave very much like text borders. Figure 2-21 shows a typical border within a spreadsheet document.
Figure 2-21 A publisher border within a spreadsheet document
Note that the border goes below the column headers (A, B, C, D) and to the right of the row labels (1, 2, 3, 4)—it should not overlap these cell boundaries. The border at the bottom and the border on the right side can be placed within the adjacent cells (outside of the cells that constitute the publisher).
Unlike borders in word-processing applications, borders in spreadsheet documents (or other documents with array data) can overlap. That is, a user can select a row of cells to be a publisher and an overlapping column of those cells to be another publisher. You should never display more than one publisher border at a time. When a user selects a spreadsheet cell that is part of more than one publisher, you should display only the border of the publisher that was last edited. (This can be accomplished by comparing the modification dates of the publishers.)
If it is absolutely necessary to display all section borders within a document at the same time, you can create a Show/Hide Borders command in the Edit menu to toggle all borders on and off.
When data is added to or deleted from a publisher that consists of a spreadsheet cell or other array, you should resize its border to accommodate the addition or deletion of data. A publisher should behave like a named range in a spreadsheet. For example, if a user cuts a row within a publisher that consists of a named range in a spreadsheet, you should shrink the publisher data and its border correspondingly.
When a user cuts a publisher and its entire contents within a spreadsheet document, the entire section should be held in the scrap. Do not leave an empty publisher border in a spreadsheet (as recommended for text borders). If a user attempts to paste a copy of an existing publisher, you should warn the user by displaying an alert box (see “Duplicating Publishers and Subscribers” on page 2-58).
Object-Oriented Graphics Borders
In an object-oriented drawing application, the publisher border should fit just around the selected objects.
You can provide resize handles that appear with all drawing objects to allow the user to resize the border of a publisher. Figure 2-22 shows a publisher border with resize handles.
Figure 2-22 A publisher border with resize handles
An application can make publisher borders appear to float over the area the user publishes. The border acts like a clipping rectangle—anything within the border becomes the publisher. Figure 2-23 shows a publisher that contains clipped graphics and its subscriber in another application.
A user can create publishers and subscribers that overlap each other. Thus, borders may overlap and it may no longer be possible to turn on a particular border when the user clicks within a publisher. Drawing applications should provide a menu command, Show Borders, that toggles to Hide Borders. This command should allow users to turn all publisher and subscriber borders on or off.
Figure 2-23
A publisher and subscriber with clipped graphics
Bitmapped Graphics Borders
Creating a border around bitmapped graphics in applications is similar to doing so in object-oriented drawing applications. The border appears around the selected area. The user can create overlapping publishers and subscribers in bitmapped graphics applications. You need to provide a Show/Hide Borders command to allow users to turn all borders on and off.
Duplicating Publishers and Subscribers
Whenever a user clicks a publisher or subscriber border, you should change the contents of the section to a selected state. You should discourage users from making multiple copies of a publisher and pasting them in the same or other documents, because the contents of the edition would be difficult or impossible to predict. Multiple copies of the same publisher also contain the same control block value. See “Creating and Registering a Section” on page 2-74 for detailed information on control blocks.
When a user attempts to create a copy of a publisher that already exists, you should display an alert box such as the one shown in Figure 2-24.
When a user attempts to save a document that contains multiple copies of the same publisher, display an alert box such as the one shown in Figure 2-25.
Figure 2-25 Saving multiple publishers alert box
If a user decides to ignore your alert box, your application should still save the document, but you should continue to display this error message every time the user saves this document.
A user can modify the contents of any duplicate publisher, but the contents of the edition will be whichever publisher was the last to write.
When a user chooses to copy and paste or duplicate a section, use the HandToHand function (described in Inside Macintosh: Memory) to duplicate the section record and alias record. Set the alias field of the cloned section record to the handle of the cloned alias record and generate a unique section identification number for it. In addition, you should also place the section data, section record, and alias record in the scrap.
Use the RegisterSection function (described in “Opening and Closing a Document Containing Sections” on page 2-22) to register the cloned section’s section record.
A user can select the contents of a publisher without selecting the border and copy just the data to a new location. In this case, the user has simply copied data (and not the publisher). Do not create a border for this data in the new location.
Modifying a Subscriber
When the user selects data or clicks the data area of a subscriber, you should highlight the entire contents of the subscriber using inverse video. Although you shouldn’t allow a user to edit the information in a subscriber, you can allow a user to make global adornments to subscribers. In other words, users can change the font, size, or other characteristics of the entire subscriber. For example, a user might select a subscriber within a document and change all text from plain to bold. However, you should discourage users from modifying the individual elements contained within a subscriber—for example, by editing a sentence or rotating an individual graphic object.
Remember that each time a new edition arrives for a subscriber, any modifications that the user has introduced are overwritten. Global changes to a subscriber are much easier for your application to regenerate.
Note
Although adornments should be global and never partial, you may still need to give users the ability to select portions of a subscriber, for instance, when performing spell checking and search-and-replace operations.u
If you do allow a user to edit a subscriber section, provide an
enable/disable editing option within the subscriber options dialog box using the SectionOptionsExpDialog function, described in “Customizing Dialog Boxes” beginning on the next page. When you allow a user to edit a subscriber, you should change the subscriber from a selected state to editable data.
Because a user can modify a publisher just like any other portion of a document, its subscriber may change in size as well as content. For example, a user may modify a publisher by adding two additional columns to a spreadsheet.
Relocating an Edition
In the Finder, users cannot move an edition across volumes. To relocate an edition, the user must first select its publisher and cancel the section (remember to remove the border). The user needs to republish and then select a new volume location for the edition. As a convenience for the user, you should retain the selection of all the publisher data after the user cancels the section to make it easy to republish the section.
Customizing Dialog Boxes
The expandable dialog box functions allow you to add items to the bottom of the dialog boxes, apply alternate mapping of events to item hits, apply alternate meanings to the item hits, and choose the location of the dialog boxes. See the chapter “Dialog Manager” in Inside Macintosh: Macintosh Toolbox Essentials and the chapter “Standard File Package” in Inside Macintosh: Files for additional information.
The expandable versions of these dialog boxes require five additional parameters. Use the NewPublisherExpDialog function to expand the publisher dialog box.
The reply parameter is a pointer to a NewPublisherReply, NewSubscriberReply, or SectionOptionsReply record, respectively.
You can automatically center the dialog box by passing (–1, –1) in the where parameter.
The expansionDITLresID parameter should contain 0 or a valid item list ('DITL') resource ID. This integer is the resource ID of an item list whose items are appended to the end of the standard item list. The dialog items keep their relative positions, but they are moved as a group to the bottom of the dialog box. See the chapter “Dialog Manager” in Inside Macintosh: Macintosh Toolbox Essentials for additional information on item lists.
The filterProc parameter should be a pointer to an expandable modal-dialog filter function or NIL. An expandable modal-dialog filter function is similar to a modal-dialog filter function or event filter function except that an expandable modal-dialog filter function accepts two extra parameters. The ModalDialog procedure calls the expandable modal-dialog filter function you provide in this parameter.
Providing a filter function enables you to map real events (such as a mouse-down event) to an item hit (such as clicking the Cancel button). For instance, you may want to map a keyboard equivalent to an item hit. See the chapter “Dialog Manager” in Inside Macintosh: Macintosh Toolbox Essentials for information on the ModalDialog procedure.
The dlgHook parameter should be a pointer to an expandable dialog hook function or NIL. An expandable dialog hook function is similar to a dialog hook function except that an expandable dialog hook function accepts an additional parameter. The NewSubscriberExpDialog, NewPublisherExpDialog, and SectionOptionsExpDialog functions call your expandable dialog hook function after each call to the ModalDialog procedure. The dialog hook function should take the appropriate action, such as filling in a checkbox. The itemOffset parameter to the procedure is the number of items in the item list before the expansion dialog items. You need to subtract the item offset from the item hit to get the relative item number in the expansion dialog item list. The expandable dialog hook function should return as its function result the absolute item number.
When the Edition Manager displays subsidiary dialog boxes in front of another dialog box on the user’s screen, your dialog hook and event filter functions should check the refCon field in the WindowRecord data type (from the window field in the DialogRecord) to determine which window is currently in the foreground. The main dialog box for the NewPublisherExpDialog and the NewSubscriberExpDialog functions contains the following constant:
CONST sfMainDialogRefCon = 'stdf'; {new publisher and }
{ new subscriber}
The main dialog box for the SectionOptionsExpDialog function contains the following constant:
See “Summary of the Edition Manager” beginning on page 2-106 for additional constants.
The yourDataPtr parameter is reserved for your use. It is passed back to your dialog hook and event filter function. This parameter does not have to be of type Ptr—it can be any 32-bit quantity that you want. In Pascal, you can pass yourDataPtr in register A6 , and declare your dialog hook and modal-dialog filter as local functions without the last parameter. The stack frame is set up properly for these functions to access their parent local variables. See the chapter “Standard File Package” in Inside Macintosh: Files for detailed information.
For the NewPublisherExpDialog and NewSubscriberExpDialog functions, all the pseudo-items for the Standard File Package—such as sfHookFirstCall(–1), sfHookNullEvent(100), sfHookRebuildList(101), and sfHookLastCall(–2)—can be used, as well as emHookRedrawPreview(150).
For the SectionOptionsExpDialog function, the only valid pseudo-items are sfHookFirstCall(–1), sfHookNullEvent(100), sfHookLastCall(–2), emHookRedrawPreview(150), emHookCancelSection(160), emHookGoToPublisher(161), emHookGetEditionNow(162), emHookSendEditionNow(162), emHookManualUpdateMode(163), and emHookAutoUpdateMode(164). See the chapter “Standard File Package” in Inside Macintosh: Files for information on pseudo-items.
Subscribing to Non-Edition Files
Using the Edition Manager, a subscriber can read data directly from another document, such as an entire 'PICT' file, instead of subscribing to an edition. This feature is for advanced applications that can set up bottleneck procedures for reading. Figure 2-26 shows a document that is subscribing directly to a 'PICT' file.
Figure 2-26 Subscribing directly to a 'PICT' file
For each application, the Edition Manager keeps a pointer to a bottleneck function. The Edition Manager never opens or closes an edition container directly. Instead, the Edition Manager calls the current edition opener. The InitEditionPack function (described on page 2-74) sets up the current system opener function.
To override the standard opener function, create an opener function that contains the following parameters:
FUNCTION MyOpener (selector: EditionOpenerVerb;
VAR PB: EditionOpenerParamBlock): OSErr;
Your opener needs to know which formats the file contains and how the data is supposed to be read or written.
The opener function is passed an edition opener verb in the selector parameter, which identifies the action the opener function should perform. The opener can allocate a handle or pointer to contain information such as file reference numbers. This value is passed to the I/O routines in the ioRefNum field of the edition opener parameter block.
The eoOpen and eoOpenNew edition opener verbs (described in “Calling an Edition Opener” on page 2-64) return a pointer to a function to do the actual reading and writing.
The following sections describe
n how to get the current edition opener
n how to set your own edition opener
n how to call an edition opener
n the edition opener parameters
Getting the Current Edition Opener
When you want to get the current edition opener, use the GetEditionOpenerProc function.
err := GetEditionOpenerProc(opener);
The opener parameter returns a pointer to the current edition opener. A different current opener is kept for each application. One application’s opener is never called by another application.
Setting an Edition Opener
You can provide your own edition opener. To do so, use the SetEditionOpenerProc function.
err := SetEditionOpenerProc(@MyOpener);
The @MyOpener parameter is a pointer to the edition opener function that you are providing. If you set the current opener to be a routine in your own code, be sure to call the GetEditionOpenerProc function first so that you can save the previous opener. If your opener is passed a selector that it does not understand, use the previous opener provided by the Edition Manager to handle it. See the next section for a list of selectors.
Calling an Edition Opener
You use the CallEditionOpenerProc function to call an edition opener. Since the Edition Manager is a package that may move, a real pointer cannot be safely returned for the standard opener and I/O routines. The system opener and the
I/O routines are returned as a value that is not a valid address to a procedure. The CallEditionOpenerProc and CallFormatIOProc functions check for these values and call the system openers.
You should never assume that a value for a system opener is a fixed constant.
Set the selector parameter to one of the edition opener verbs. The edition opener verbs include
n eoCanSubscribe
n eoOpen
n eoClose
n eoOpenNew
n eoCloseNew
The PB parameter of the CallEditionOpenerProc function is an edition opener parameter block.
TYPE EditionOpenerParamBlock =
RECORD
info: EditionInfoRecord; {edition container to }
{ be subscribed to}
sectionH: SectionHandle; {publisher or }
{ subscriber }
{ requesting open}
document: FSSpecPtr; {document passed}
fdCreator: OSType; {Finder creator type}
ioRefNum: LongInt; {reference number}
ioProc: FormatIOProcPtr; {routine to read }
{ formats}
success: Boolean; {reading or writing }
{ was successful}
formatsMask: SignedByte; {formats required to }
{ subscribe}
END;
The routine parameter of the CallEditionOpenerProc function is a pointer to an edition opener function.
The following list shows which fields of the edition opener parameter block are used by the edition opener verbs:
Opener verb Field Description Called by (continued)
eoCanSubscribe Æ info Edition container to subscribe to. NewSubscriberDialogfunction for a subscriber
Æ formatsMask Formats required to subscribe.
¨ Return value A noErr code indicates that an edition container can be subscribed to. A noTypeErr code indicates that an edition container cannot be subscribed to.
eoOpen Æ info Edition container to open for reading. OpenEdition and GetStandardFormats functions for a subscriber
Æ sectionH Subscriber section requesting open or NIL.
¨ ioRefNum Reference number for use by I/O routine. Not the same as EditionRefNum.
¨ ioProc I/O routine to call to read formats.
¨ Return value A noErr code or appropriate error code.
eoClose Æ info Edition container to be closed for reading. CloseEdition and GetStandardFormats functions for a subscriber
Æ sectionH Subscriber section requesting close or NIL.
Æ ioRefNum Value returned by eoOpen.
Æ ioProc Value returned by eoOpen.
Æ success Success value passed to the CloseEdition function.
¨ Return value A noErr code or appropriate error code.
continued
eoOpenNew Æ info Edition container to open for writing. OpenNewEdition function for a publisher
Æ sectionH Publisher section requesting open or NIL.
Æ document Document pointer passed into the OpenNewEdition function.
Æ fdCreator The fdCreator passed into the OpenNewEdition function.
¨ ioRefNum Reference number for use by I/O routine. Not the same as EditionRefNum.
¨ ioProc I/O routine to call to write formats.
¨ Return value A noErr code or appropriate error code.
eoCloseNew Æ info Edition container to be closed after writing. CloseEdition function for a publisher
Æ sectionH Publisher section requesting close or NIL.
Æ ioRefNum Value returned by eoOpenNew.
Æ ioProc Value returned by eoOpenNew.
Æ success Success value passed to the CloseEdition function.
¨ Return value A noErr code or appropriate error code.
As Listing 2-9 demonstrates, you install your own edition opener function by first saving the current opener and then installing your own opener. The listing also shows an edition opener, the MyEditionOpener function. When it receives the eoCanSubscribe opener verb, the MyEditionOpener function calls another application-defined routine, MyCanSubscribe. The Edition Manager sends your edition opener this verb to help it build the list of files displayed by the NewSubscriber function. The MyCanSubscribe function returns noErr if it can subscribe to the file; otherwise, it calls the original edition opener to handle the request.
Each time the Edition Manager opens or closes an edition container, it calls the current edition opener procedure and passes it an opener verb and a parameter block.
Your opener must be careful when closing documents since a document may already have been opened by another application. Be sure to use the Open/Deny modes whenever possible. Do not close a document if it was already open when your application opened it.
Listing Files That Can Be Subscribed To
The NewSubscriberDialog function calls the edition opener function and passes the eoCanSubscribe opener verb in the selector parameter to build the list of files that can be subscribed to. The preview in the subscriber dialog box is generated by calling the GetStandardFormats function (described in “Edition Container Formats” on page 2-101), which calls the format I/O procedure with the verbs eoOpen, ioHasFormat, ioRead, and then eoClose. See “Calling a Format I/O Function” on this page for detailed information on format I/O verbs.
Reading From and Writing to Files
The I/O procedure is a routine that actually reads and writes the data. It too has an interface of a selector and a parameter block.
To override the standard reading and writing functions, create an I/O function. Note that you also need to provide your own opener function to call your I/O function. See “Calling an Edition Opener” on page 2-64.
FUNCTION MyIO (selector: FormatIOVerb;
VAR PB: FormatIOParamBlock): OSErr;
Calling a Format I/O Function
To indicate to the Edition Manager which format I/O function to use, use the CallFormatIOProc function.
err := CallFormatIOProc (selector, PB, routine);
Set the selector parameter to one of the format I/O verbs. The format I/O verbs include
n ioHasFormat
n ioReadFormat
n ioNewFormat
n ioWriteFormat
The PB parameter of the CallFormatIOProc function contains a format I/O parameter block.
The routine parameter of the CallFormatIOProc function is a pointer to a format
I/O function.
The following list shows which fields of FormatIOParamBlock are used by the format I/O verbs:
Format I/O verb Parameter Description Called by (continued)
ioHasFormat Æ ioRefNum I/O reference number returned by opener. EditionHasFormat, GetStandardFormats, and ReadEdition functions
Æ format Check for this format.
¨ formatIndex An optional enumeration of the supplied format.
¨ buffLen If found, return the length size or –1 if size is unknown.
¨ Return value A noErr or noTypeErr code.
continued
ioReadFormat Æ ioRefNum I/O reference number returned by opener. ReadEdition and GetStandardFormats functions
Æ format Get this format.
Æ formatIndex Value returned by ioHasFormat.
Æ offset Read format beginning from this offset.
Æ buffPtr Put data beginning here.
´ buffLen Specify buffer length to read, and return actual amount received.
¨ Return value A noErr code, or appropriate error code.
ioNewFormat Æ ioRefNum I/O reference number returned by opener. SetEditionFormatMarkand WriteEdition functions
Æ format Create this format.
¨ formatIndex An optional enumeration of the supplied format.
¨ Return value A noErr code, or appropriate error code.
ioWriteFormat Æ ioRefNum I/O reference number returned by opener. WriteEdition function
Æ format Get this format.
Æ formatIndex Value returned by ioNewFormat.
Æ offset Write format beginning from this offset.
Æ buffPtr Get data beginning here.
´ buffLen Specify buffer length to write.
¨ Return value A noErr code or appropriate error code.
The marks for each format are kept by the Edition Manager. The format I/O function only needs to be able to read or write, beginning at any offset. If you know that your application always reads an entire format sequentially, you can ignore the offset.
Edition Manager Reference
This section describes the data structures and routines that are specific to the Edition Manager. The “Data Structures” section describes the edition container record and the section record. The “Edition Manager Routines” section describes the routines your application can use to implement publish and subscribe features in your application.
Data Structures
This section describes the edition container record and the section record. See page 2-91 for a description of the new subscriber reply record, page 2-93 for a description of the new publisher reply record, page 2-95 for a description of the section options record, and page 2-99 for a description of the edition info record. For information on the edition opener parameter block and format I/O parameter block, see page 2-103 and page 2-104, respectively.
The Edition Container Record
An edition container record identifies a specific edition file. Many Edition Manager routines require an edition container record as a parameter. The EditionContainerSpec data type defines an edition container record.
TYPE EditionContainerSpec =
RECORD
theFile: FSSpec; {file containing edition }
{ data}
theFileScript: ScriptCode; {script code of filename}
thePart: LongInt; {which part of file, }
{ always kPartsNotUsed}
thePartName: Str31; {reserved}
thePartScript: ScriptCode; {reserved}
END;
Field descriptions
theFile A file specificiation record that identifies the name and location of the edition file. Specify the file using the standard conventions for file specification records as described in the chapter “Introduction to File Management” in Inside Macintosh: Files.
theFileScript A script code that identifies the script in which the name of the document is to be displayed in the Finder. A script code of smSystemScript represents the default system script.
thePart A value that must always be set to kPartsNotUsed in System 7.
thePartName Reserved.
thePartScript Reserved.
The Section Record
A section record identifies a specific publisher or subscriber section. It contains information to identify the section as a publisher or a subscriber, a time stamp to record the last modification of the section, and unique identification for each section. Many Edition Manager routines require a handle to a section record as a parameter. The SectionRecord data type defines a section record.
TYPE SectionRecord =
RECORD
version: SignedByte; {always 1 in 7.0}
kind: SectionType; {publisher or subscriber}
mode: UpdateMode; {automatic or manual}
mdDate: TimeStamp; {last change in document}
sectionID: LongInt; {application-specific, }
{ unique per document}
refCon: LongInt; {application-specific}
alias: AliasHandle; {handle to alias record}
{The following fields are private and are set up by the }
{ RegisterSection function. Do not modify the private }
{ fields.}
subPart: LongInt; {private}
nextSection: SectionHandle; {private, do not use as a }
{ linked list}
controlBlock: Handle; {may be used for comparison }
{ only}
refNum: EditionRefNum; {private}
END;
Field descriptions
version Indicates the version of the section record, currently $01.
kind Defines the section type as either publisher or subscriber with the stPublisher or stSubscriber constant.
mode Indicates if editions are updated automatically or manually.
mdDate Indicates which version (modification date) of the section’s contents is contained within the publisher or subscriber. The mdDate field is set to 0 when you create a new subscriber section and to the current time when you create a new publisher. Be sure to update this field each time publisher data is modified. The section’s modification date is compared to the edition’s modification date to determine whether the section and the edition contain the same data. The section modification date is displayed in the publisher and subscriber options dialog boxes. See “Closing an Edition” on page 2-28 for detailed information.
sectionID Provides a unique number for each section within a document. A simple way to implement this is to create a counter for each document that is saved to disk with the document. The counter should start at 1. The section ID is currently used as a tie breaker in the GoToPublisherSection function when there are multiple publishers to the same edition in a single document. The section ID should not be 0 or –1. See “Duplicating Publishers and Subscribers” on page 2-58 for information on multiple publishers.
refCon Reference constant available for application-specific use.
alias Contains a handle to the alias record for a particular section within a document.
Whenever the user creates a publisher or subscriber, call the NewSection function (described on page 2-75) to create a section record and alias record.
Edition Manager Routines
This section describes the routines you use to
n initialize the Edition Manager
n create and register a section
n create and delete an edition container
n set and locate a format mark
n read in edition data
n write out edition data
n close an edition after reading or writing
n display dialog boxes
n locate a publisher and edition from a subscriber
n read and write non-edition files
Result codes appear at the end of each function where applicable. In addition to the specific result codes listed, you may receive errors generated by the Alias Manager, File Manager, and Memory Manager.
Initializing the Edition Manager
You use the InitEditionPack function to initialize the Edition Manager. Note that you should call this function only once.
InitEditionPack
Before calling the InitEditionPack function, be sure to determine whether the Edition Manager is available on your system by using the Gestalt function with the gestaltEditionMgrAttr ('edtn') selector.
FUNCTION InitEditionPack: OSErr;
DESCRIPTION
The InitEditionPack function returns an error if the package could not be loaded into the system heap and properly initialized.
RESULT CODESnoErr 0 No error
memFullErr –108 Could not load package
Creating and Registering a Section
You use the NewSection function to create a new section (either publisher or subscriber) and alias record (which is a reference to the edition container from the document containing the publisher or subscriber section).
The NewSection function registers a section much as the RegisterSection function informs the Edition Manager about a section (except that the NewSection function does not resolve an alias to find the edition container).
When a section needs to be disposed of because the document containing the section is being closed or because the user has canceled the section, you need to call the UnRegisterSection function before disposing of the section.
Using the IsRegisteredSection function, your application must verify that each event received is for a registered section. This is necessary because your application may have just called UnRegisterSection while the event was already being held in the event queue.
If a user saves a document that contains sections under another name (using Save As) or pastes a portion of a document that contains a section into another document, use the AssociateSection function to update the section’s alias record.
NewSection
Use the NewSection function to create a new section record and alias record for a new publisher or subscriber.
FUNCTION NewSection (container: EditionContainerSpec;
sectionDocument: FSSpecPtr;
kind: SectionType; sectionID: LongInt;
initialMode: UpdateMode;
VAR sectionH: SectionHandle): OSErr;
container The edition you want to publish or subscribe to.
sectionDocument
The volume reference number, directory ID, and filename of the document that contains a section. The sectionDocument parameter can be NIL if your current document has never been saved. If so, when the user finally saves the document, remember to call the AssociateSection function for each section to update its alias record.
kind The type of section (publisher or subscriber) being created.
sectionID A unique number for a section within a document. The NewSection function initializes the sectionID field of the new section record with the specified value. Do not use 0 or –1 for an ID number; these numbers are reserved. If your application copies a section, you need to specify a unique number for the copied section.
initialMode
The update mode for the section. For publishers this is either the pumOnSave or pumManual constant, and for subscribers it is either sumAutomatic or sumManual. A subscriber created with sumAutomatic mode automatically receives a Section Read event. To prevent this initial Section Read event, you should set the initialMode parameter to sumManual and then, when NewSection returns, set the mode field of the section record to sumAutomatic.
sectionH The NewSection function returns a handle to the allocated section record in this parameter. If an error occurs, NewSection returns NIL in this parameter.
DESCRIPTION
The NewSection function allocates two handles in the current zone: one handle for the section record and another handle for the alias record. Note that you are responsible for unregistering handles created by the Edition Manager.
Your application receives the multiplePublisherWrn result code if there is another registered publisher to the same edition. Your application receives the notThePublisherWrn result code if another publisher (to the same edition) was the last section to write to the edition. The multiplePublisherWrn result code takes priority over the notThePublisherWrn result code.
RESULT CODESnoErr 0 No error
editionMgrInitErr –450 Manager not initialized
badSectionErr –451 Not a valid section type
badSubPartErr –454 Bad edition container spec
multiplePublisherWrn –460 Already is a publisher
notThePublisherWrn –463 Not the publisher
SEE ALSO
For information on the edition container record, see page 2-71. For information on the section record, see “The Section Record” beginning on page 2-72. For information on file specification records, see Inside Macintosh: Files. See Listing 2-4 on page 2-33 for an example that uses NewSection to create a publisher and Listing 2-6 on page 2-40 for an example that creates a subscriber using NewSection.
RegisterSection
When opening a document that contains sections, register each section using the RegisterSection function.
FUNCTION RegisterSection (sectionDocument: FSSpec;
sectionH: SectionHandle;
VAR aliasWasUpdated: Boolean): OSErr;
sectionDocument
The volume reference number, directory ID, and filename of the document that contains a section.
sectionH A handle to the section record for a given section.
aliasWasUpdated
A Boolean value that returns TRUE if the alias for the edition container subscribed to was out of date and was updated. This may occur if the edition file was moved to a new location or was renamed.
DESCRIPTION
The RegisterSection function adds the section record to the Edition Manager’s list of registered sections and tries to allocate a control block. After calling the RegisterSection function, the controlBlock field of the section record contains either NIL or a valid control block.
For a subscriber, the controlBlock field contains NIL if the RegisterSection function could not locate the edition container being subscribed to. The RegisterSection function then returns either the containerNotFoundWrn or the userCanceledErr result code. For a publisher, if the RegisterSection function could not locate its corresponding edition container, the Edition Manager creates an edition container in the last place the edition was located and creates a control block for it. If the RegisterSection function could not locate a publisher’s corresponding edition container or its volume, the controlBlock field contains NIL. You should never re-register a section that is already registered.
Note that you can compare control blocks for individual sections. If two sections contain the same control block value, these sections publish or subscribe to the same edition (unless the control block is NIL). The Edition Manager keeps track of how many sections are referencing a control block to know when it can be deallocated. The control block maintains a count of how many sections are referencing it. Each time you use the UnRegisterSection function, the control block subtracts 1 from the number of sections. When the number of sections reaches 0, the control block is deallocated.
Your application receives the multiplePublisherWrn result code if there is another registered publisher to the same edition. Your application receives the notThePublisherWrn result code if another publisher (to the same edition) was the last section to write to the edition. The multiplePublisherWrn result code takes priority over the notThePublisherWrn result code.
RESULT CODESnoErr 0 No error
userCanceledErr –128 User clicked Cancel in dialog box
editionMgrInitErr –450 Manager not initialized
badSectionErr –451 Not valid section type
multiplePublisherWrn –460 Already is a publisher
containerNotFoundWrn –461 Alias was not resolved
notThePublisherWrn –463 Not the publisher
SEE ALSO
For information on the section record, see “The Section Record” beginning on page 2-72. For information on file specification records, see Inside Macintosh: Files. For additional information and an example of the use of RegisterSection, see “Opening and Closing a Document Containing Sections” beginning on page 2-22.
UnRegisterSection
When a section needs to be disposed of because the document containing the section is being closed or because the user has canceled the section, you need to call the UnRegisterSection function before disposing of the section.
FUNCTION UnRegisterSection (sectionH: SectionHandle): OSErr;
sectionH A handle to the section record for a given section.
DESCRIPTION
The UnRegisterSection function removes the section from the Edition Manager’s list of registered sections. You can then dispose of the section record and alias record with standard Memory Manager and Resource Manager calls. Once unregistered, a section does not receive any events and cannot read or write any data. Depending on your Clipboard strategy, you may want to unregister sections that have been cut into the Clipboard.
RESULT CODESnoErr 0 No error
fBsyErr –47 Section doing I/O
editionMgrInitErr –450 Manager not initialized
notRegisteredSectionErr –452 Not registered
IsRegisteredSection
Upon receiving a section event, your application must call the IsRegisteredSection function to verify that the event received is for a registered section. You must call IsRegisteredSection before handling a section event because your application may have just called UnRegisterSection while the event was already being held in the event queue.
FUNCTION IsRegisteredSection (sectionH: SectionHandle): OSErr;
sectionH A handle to the section record for a given section.
DESCRIPTION
The IsRegisteredSection function returns a result code (not a Boolean value) indicating whether the section is registered. A noErr result code indicates that a section is registered.
RESULT CODESnoErr 0 No error
notRegisteredSectionErr –452 Not registered
SEE ALSO
For an example of the use of IsRegisteredSection, see Listing 2-1 on page 2-14.
AssociateSection
If a user saves a document that contains sections under another name (using Save As) or pastes a portion of a document that contains a section into another document, use the AssociateSection function to update the section’s alias record.
FUNCTION AssociateSection (sectionH: SectionHandle;
newSectionDocument: FSSpecPtr): OSErr;
sectionH A handle to the section record for a given section.
newSectionDocument
The volume reference number, directory ID, and filename of the new document.
DESCRIPTION
The AssociateSection function calls UpdateAlias on the section’s alias record.
RESULT CODESnoErr 0 No error
paramErr –50 Invalid parameter
SEE ALSO
For information on the UpdateAlias function, see the chapter “Alias Manager” in Inside Macintosh: Files.
Creating and Deleting an Edition Container
Each time a user creates a new publisher section within a document to an edition that does not already exist, you use the CreateEditionContainerFile function to create an empty edition container.
To remove the edition container, use the DeleteEditionContainerFile function.
CreateEditionContainerFile
You use the CreateEditionContainerFile function to create an empty edition container.
FUNCTION CreateEditionContainerFile
(editionFile: FSSpec; fdCreator: OSType;
editionFileNameScript: ScriptCode): OSErr;
editionFile
The volume reference number, directory ID, and filename for the edition container being created.
fdCreator The creator type for the edition.
editionFileNameScript
The script of the filename. (You can get this value from the theFileScript field of an edition container specification record.)
DESCRIPTION
The CreateEditionContainerFile function creates an empty edition container file (it does not contain any formats). This function sets the file type of the edition to 'edtu'. As soon as you write data to the edition, the Edition Manager updates the type (to 'edtp' for graphics, 'edtt' for text, or 'edts' for sound). If your application writes both 'TEXT' and 'PICT' formats to the edition, the Edition Manager sets the file type to the type that was written first. If your application has a bundle, you should designate an icon for the appropriate edition types that you can write.
RESULT CODESnoErr 0 No error
dskFulErr –34 Disk is full
nsvErr –35 No such volume
ioErr –36 I/O error
bdNamErr –37 Bad filename
fnfErr –43 File not found
dirNFErr –120 Directory not found
editionMgrInitErr –450 Manager not initialized
SEE ALSO
For information on file specification records, see Inside Macintosh: Files. For an example of the use of CreateEditionContainerFile, see Listing 2-4 on page 2-33.
DeleteEditionContainerFile
If a user cancels a publisher section within a document or closes a document containing a newly created publisher without saving, you need to remove the edition container.
To locate the appropriate edition container to be deleted, use the GetEditionInfo function. You use the UnRegisterSection function (only after using the GetEditionInfo function) to unregister the section record and alias record of the publisher being canceled.
To remove the edition container, use the DeleteEditionContainerFile function.
FUNCTION DeleteEditionContainerFile (editionFile: FSSpec): OSErr;
editionFile
The volume reference number, directory ID, and filename for the edition container being deleted.
DESCRIPTION
If the user cancels a publisher, do not call the DeleteEditionContainerFile function until the user saves the document. This allows the user to undo changes and revert to the last saved version of the document.
The DeleteEditionContainerFile function deletes the edition container only if there is no registered publisher. You need to unregister a publisher before you can delete its corresponding edition container.
You should use the DeleteEditionContainerFile function even if there are subscribers to the edition. When a subscriber section tries to read in data, it receives an error if the edition container has been deleted.
RESULT CODESnoErr 0 No error
nsvErr –35 No such volume
ioErr –36 I/O error
bdNamErr –37 Bad filename
fnfErr –43 File not found
dirNFErr –120 Directory not found
editionMgrInitErr –450 Manager not initialized
SEE ALSO
See page 2-98 for detailed information on the GetEditionInfo function. See page 2-77 for information on the UnRegisterSection function. For information on file specification records, see Inside Macintosh: Files.
Setting and Getting a Format Mark
Use the SetEditionFormatMark function to set the current mark for a section format and the GetEditionFormatMark function to get the current mark for a particular format.
SetEditionFormatMark
A format mark indicates the next position of a read or write operation. Initially, a mark defaults to 0. After reading or writing data, the format mark is set past the last position written to or read from. To set the current mark for a given format, use the SetEditionFormatMark function.
FUNCTION SetEditionFormatMark (whichEdition: EditionRefNum;
whichFormat: FormatType;
setMarkTo: LongInt): OSErr;
whichEdition
The reference number for the edition.
whichFormat
The format type for the edition.
setMarkTo The offset for the next read or write for this format.
DESCRIPTION
The SetEditionFormatMark function sets the current mark for the specified format type according to the value of the setMarkTo parameter.
RESULT CODESnoErr 0 No error
rfNumErr –51 Bad edition reference number
noTypeErr –102 Unknown format (subscriber only)
editionMgrInitErr –450 Manager not initialized
GetEditionFormatMark
Use the GetEditionFormatMark function to get the current mark for a particular format.
FUNCTION GetEditionFormatMark (whichEdition: EditionRefNum;
whichFormat: FormatType;
VAR currentMark: LongInt): OSErr;
whichEdition
The reference number for the edition.
whichFormat
The format type whose mark you want to get.
currentMark
The GetEditionFormatMark function returns the mark for the specified format in this parameter.
DESCRIPTION
If the edition does not support the format specified in the whichFormat parameter, you receive a noTypeErr result code.
RESULT CODESnoErr 0 No error
rfNumErr –51 Bad edition reference number
noTypeErr –102 Unknown format
editionMgrInitErr –450 Manager not initialized
Reading in Edition Data
To initiate the reading of data from an edition (for a subscriber), use the OpenEdition function.
Use the EditionHasFormat function to learn in which formats the edition data is available.
Use the ReadEdition function to read data from an edition. This function reads from the current mark for the specified format.
OpenEdition
To initiate the reading of data from an edition (for a subscriber), use the OpenEdition function.
FUNCTION OpenEdition (subscriberSectionH: SectionHandle;
VAR refNum: EditionRefNum): OSErr;
subscriberSectionH
A handle to the section record for a given section.
refNum The OpenEdition function returns the reference number for the edition in this parameter.
DESCRIPTION
The OpenEdition function opens an edition for reading and returns a reference number that your application can use to refer to this edition in other Edition Manager routines. Multiple subscribers can each call the OpenEdition function simultaneously (each call returns a different reference number) and read data from a single edition. If a publisher (located on a different machine) is writing to an edition when you use the OpenEdition function, you receive an flLckedErr result code.
RESULT CODESnoErr 0 No error
fnfErr –43 File not found
flLckedErr –45 Publisher writing to an edition
permErr –54 Not a subscriber
editionMgrInitErr –450 Manager not initialized
SEE ALSO
For an example of the use of OpenEdition, see Listing 2-7 on page 2-42.
EditionHasFormat
Use the EditionHasFormat function to learn in which formats the edition data is available.
FUNCTION EditionHasFormat (whichEdition: EditionRefNum;
whichFormat: FormatType;
VAR formatSize: Size): OSErr;
whichEdition
The reference number for the edition.
whichFormat
The format type that you are requesting. For the whichFormat parameter, you should decide which formats to read in the same way that you do when reading data from the scrap. You can also get a list of all the available formats and their respective lengths by reading the kFormatListFormat ('fmts') format.
formatSize
The EditionHasFormat function returns the format length in this parameter.
DESCRIPTION
If the requested format is available, the EditionHasFormat function returns noErr, and the formatSize parameter returns the size of the data in the specified format or kFormatLengthUnknown (–1), which signifies that the size is unknown. You should therefore continue to read the format until there is no more data.
Note
Note
The Translation Manager (if it is available) attempts implicit translation under certain circumstances. For instance, it does so when your application attempts to read from an edition a format type that is not in the edition. In this case, the Translation Manager attempts to translate the data into the requested format. For more information, see the chapter “Translation Manager” in Inside Macintosh: More Macintosh Toolbox.u
RESULT CODESnoErr 0 No error
rfNumErr –51 Bad edition reference number
noTypeErr –102 Format not available
editionMgrInitErr –450 Manager not initialized
SEE ALSO
For an example of the use of EditionHasFormat, see Listing 2-7 beginning on page 2-42. For information about the Translation Manager and Scrap Manager, see Inside Macintosh: More Macintosh Toolbox.
ReadEdition
Use the ReadEdition function to read data from an edition. This function reads from the current mark for the specified format.
FUNCTION ReadEdition (whichEdition: EditionRefNum;
whichFormat: FormatType; buffPtr: UNIV Ptr;
VAR buffLen: Size): OSErr;
whichEdition
The reference number for the edition.
whichFormat
The format type that you want to read.
buffPtr A pointer to the buffer into which you want to read the data.
buffLen The number of bytes that you want to read into the buffer. The ReadEdition function returns the actual number of bytes read in the buffLen parameter.
DESCRIPTION
The ReadEdition function reads data from the edition into the specified buffer. ReadEdition returns in the buffLen parameter the total number of bytes read into the buffer. If the buffLen parameter returns a value smaller than the value you have specified, there is no additional data to read, and the ReadEdition function returns a noErr result code. If you use the ReadEdition function after all data is read in, the ReadEdition function returns an eofErr result code.
You can read data from an edition while a publisher on the same machine is writing data to the same edition. The data that you are reading is the old edition (not the data that the publisher is writing). If the publisher finishes writing data before you are through reading the old edition data, the ReadEdition function returns an abortErr result code. If the ReadEdition function returns an abortErr result code, you should stop trying to read data and use the CloseEdition function with the successful parameter set to FALSE.
Note
The Translation Manager (if it is available) attempts implicit translation under certain circumstances. For instance, it does so when your application attempts to read from an edition a format type that is not in the edition. In this case, the Translation Manager attempts to translate the data into the requested format. For more information, see the chapter “Translation Manager” in Inside Macintosh: More Macintosh Toolbox.u
RESULT CODESnoErr 0 No error
abortErr –27 Publisher has written a new edition
ioErr –36 I/O error
fnOpnErr –38 File not open
eofErr –39 No more data of that format
rfNumErr –51 Bad edition reference number
noTypeErr –102 Format not available
editionMgrInitErr –450 Manager not initialized
SEE ALSO
For an example of the use of ReadEdition, see Listing 2-7 beginning on page 2-42.
Writing out Edition Data
To initiate the writing of data from a publisher to its edition container, use the OpenNewEdition function. (To create an edition container, use the CreateEditionContainerFile function, as described on page 2-79.)
Use the WriteEdition function to write data to an edition.
OpenNewEdition
To initiate the writing of data from a publisher to its edition container, use the OpenNewEdition function.
FUNCTION OpenNewEdition (publisherSectionH: SectionHandle;
fdCreator: OSType;
publisherSectionDocument: FSSpecPtr;
VAR refNum: EditionRefNum): OSErr;
publisherSectionH
The publisher section that is writing to the edition.
fdCreator The Finder creator type of the new edition icon.
publisherSectionDocument
The document that contains the publisher. This parameter is used to create an alias from the edition to the publisher’s document. If you pass NIL for publisherSectionDocument, an alias is not made in the edition file.
refNum The OpenNewEdition function returns the reference number for the edition in this parameter. You specify this reference number as a parameter for subsequent calls to WriteEdition, SetEditionFormatMark, and CloseEdition to specify which publisher is writing its data to an edition. If the edition cannot be opened for writing because there is another publisher writing to it, or because the file system does not allow writing, an error is returned and OpenNewEdition sets refNum to NIL.
DESCRIPTION
The OpenNewEdition function opens an edition for writing. The function returns an flLckdErr result code if there is a subscriber on another machine reading data from the same edition. The OpenNewEdition function returns a permErr result code if there is a registered publisher to that edition on another machine.
The Edition Manager allows two registered publishers that are located on the same machine to write to the same edition. Note that multiple publishers cannot write to the same edition simultaneously—only one publisher can write to an edition at a given time.
RESULT CODESnoErr 0 No error
ioErr –36 I/O error
flLckdErr –45 Edition in use by another section
permErr –54 Registered publisher on another machine
wrPermErr –61 Not a publisher
editionMgrInitErr –450 Manager not initialized
SEE ALSO
For an example of the use of OpenNewEdition, see Listing 2-5 beginning on
page 2-36.
WriteEdition
Use the WriteEdition function to write data to an edition. This function begins writing at the current mark for the specified format.
FUNCTION WriteEdition (whichEdition: EditionRefNum;
whichFormat: FormatType;
buffPtr: UNIV Ptr; buffLen: Size): OSErr;
whichEdition
The reference number for the edition.
whichFormat
The format type that you want to write.
buffPtr A pointer to the buffer containing the data to write to the edition.
buffLen The number of bytes that you want to write to the edition.
DESCRIPTION
The WriteEdition function writes the specified number of bytes to the edition. If the data cannot be entirely written to the edition, the WriteEdition function returns an error.
RESULT CODESnoErr 0 No error
dskFulErr –34 Disk is full
ioErr –36 I/O error
rfNumErr –51 Bad edition reference number
editionMgrInitErr –450 Manager not initialized
SEE ALSO
For an example that writes data to an edition, see Listing 2-5 beginning on page 2-36.
Closing an Edition After Reading or Writing
After finishing reading from or writing to an edition, use the CloseEdition function to close the edition.
CloseEdition
Use the CloseEdition function to close an edition after you finish reading from or writing to it.
FUNCTION CloseEdition (whichEdition: EditionRefNum;
successful: Boolean): OSErr;
whichEdition
The reference number for the edition.
successful
A value that indicates whether your application was successful (TRUE) or unsuccessful (FALSE) in reading from or writing data to the edition.
DESCRIPTION
When a subscriber successfully finishes reading data from the edition, the CloseEdition function takes the modification date of the edition file that you have read and puts it in the mdDate field of the subscriber’s section record. This indicates that the data contained in the edition and the subscriber section within the document are the same.
When a subscriber is unsuccessful in reading data from an edition (because there is not enough memory, or you didn’t find a format that you can read), set the successful parameter to FALSE. The CloseEdition function then closes the edition, but does not set the mdDate field. This implies that the subscriber is not updated with the latest edition.
When a publisher successfully finishes writing data to an edition, the CloseEdition function makes the data that the publisher has written to the edition available to any subscribers and sets the corresponding edition file’s modification date (ioFlMdDat) to the mdDate field of the publisher’s section record. The Edition Manager then sends a Section Read event to all current subscribers set to automatic update mode. At this point, the file type of the edition file is set based on the first known format that the publisher wrote.
When a publisher is unsuccessful in writing data to an edition, the CloseEdition function discards what the publisher has written to the edition. The data contained in the edition prior to writing remains unchanged, and Section Read events are not sent to subscribers.
RESULT CODESnoErr 0 No error
ioErr –36 I/O error
fnOpnErr –38 File not open
rfNumErr –51 Bad edition reference number
editionMgrInitErr –450 Manager not initialized
SEE ALSO
For an example of the use of CloseEdition, see Listing 2-5 beginning on
page 2-36.
Displaying Dialog Boxes
The Edition Manager supports three dialog boxes: publisher, subscriber, and options dialog boxes. Your application can display simple dialog boxes that appear centered on the user’s screen, or you can customize your dialog boxes.
Use the GetLastEditionContainerUsed function to get the default edition to display.
Use the NewSubscriberDialog function to display the subscriber dialog box on the user’s screen and use the NewPublisherDialog function to display the publisher dialog box on the user’s screen. Unlike the Standard File Package routines, the NewPublisherDialog and the NewSubscriberDialog functions allow you to specify the initial volume reference number and directory ID so that there can be one default location for editions for all applications.
You use the SectionOptionsDialog function to display the publisher options and subscriber options dialog boxes on the user’s screen.
The NewSubscriberExpDialog, NewPublisherExpDialog, and SectionOptionsExpDialog functions are the same as the simple dialog functions but have five additional parameters.
GetLastEditionContainerUsed
Use the GetLastEditionContainerUsed function to get the default edition to display. This function allows a user to easily subscribe to the data recently published.
FUNCTION GetLastEditionContainerUsed
(VAR container: EditionContainerSpec): OSErr;
container If the GetLastEditionContainerUsed function locates the last edition for which a section was created, the container parameter contains its volume reference number, directory ID, filename, and part, and returns a noErr result code. (The last edition created is associated with the last time that your application or another application located on the same machine used the NewSection function.)
DESCRIPTION
If the last edition used is missing, the GetLastEditionContainerUsed function returns an fnfErr result code, but still returns the correct volume reference number and directory ID that you should use for the NewSubscriberDialog function.
Pass the information from the GetLastEditionContainerUsed function to the NewSubscriberDialog function.
RESULT CODESnoErr 0 No error
fnfErr –43 Edition container not found
editionMgrInitErr –450 Manager not initialized
SEE ALSO
For an example of the use of GetLastEditionContainerUsed, see Listing 2-6 beginning on page 2-40. For a description of the edition container record, see page 2-71. The NewSubscriberDialog function is described next.
NewSubscriberDialog
When a user chooses the Subscribe To menu command, your application should call the NewSubscriberDialog function to allow the user to choose an edition to subscribe to.
FUNCTION NewSubscriberDialog
(VAR reply: NewSubscriberReply): OSErr;
reply The new subscriber reply record. You specify a location to use as the default edition container in the container field of this record. You also specify in the formatsMask field which edition format types NewSubscriberDialog should display. The NewSubscriberDialog function returns information concerning the user’s choice in the canceled and container fields of this record.
canceled The NewSubscriberDialog function returns in this field a value that indicates whether the user canceled the dialog box. The function returns TRUE in the canceled field if the user canceled the dialog box. Otherwise, the function returns FALSE in this field and returns in the container field the edition container for the new subscriber.
formatsMask The formatsMask field indicates which edition format type (text, graphics, and sound) to display within the subscriber dialog box. You can set the formatsMask field to the following constants: kTEXTformatMask (1), kPICTformatMask (2), or ksndFormatMask (4). To support a combination of formats, add the constants together. For example, a formatsMask of 3 displays both graphics and text edition format types in the subscriber dialog box.
container The edition container of the last edition published or subscribed to. You provide in this parameter the location and filename to use as the default edition to subscribe to. If the user clicks the Subscribe button, NewSubscriberDialog returns FALSE in the canceled field and returns the selected edition container for the new subscriber in the container field.
DESCRIPTION
The NewSubscriberDialog function displays the subscriber dialog box on the user’s screen. The NewSubscriberDialog function (which is based on the CustomGetFile procedure described in the chapter “Standard File Package” in Inside Macintosh: Files) switches to the volume reference number and directory ID and selects the filename of the edition container that you specified in the container field of the reply parameter. Use the GetLastEditionContainerUsed function to get the edition container of the last edition that was either published or subscribed to, then set the container field to this edition container. This allows the user to publish and then easily subscribe.
Note that if an edition does not contain either 'PICT', 'TEXT', or 'snd ' data, the NewSubscriberDialog function does not list the edition file in the new subscriber dialog box (unless you install an opener that can recognize the edition’s data in response to the eoCanSubscribe verb).
RESULT CODESnoErr 0 No error
editionMgrInitErr –450 Manager not initialized or could not load package
badSubPartErr –454 Bad edition container spec
SEE ALSO
For an illustration of the new subscriber dialog box, see Figure 2-12 on page 2-37. For an example of the use of NewSubscriberDialog, see Listing 2-6 beginning on page 2-40. For a description of the edition container record, see page 2-71. For information on edition openers, see “Subscribing to Non-Edition Files” beginning on page 2-62.
NewPublisherDialog
When a user selects a portion of a document and then chooses the Create Publisher menu command, your application should call the NewPublisherDialog function to allow the user to choose a name and location of the edition to which your application writes the publisher data. Your application specifies a location and name to use as the default edition and provides a preview of the publisher data to the NewPublisherDialog function.
FUNCTION NewPublisherDialog
(VAR reply: NewPublisherReply): OSErr;
reply A new publisher reply record. You specify a location to use as the default edition container in the container field of this record. You also specify information in the usePart, preview, and previewFormat fields. The NewPublisherDialog function returns information concerning the user’s choice in the canceled, replacing, and container fields of this record.
TYPE NewPublisherReply =
RECORD
canceled: Boolean; {user canceled dialog box}
replacing: Boolean; {user chose existing }
{ filename for an edition}
usePart: Boolean; {always false in version 7.0}
preview: Handle; {handle to 'prvw', 'PICT', }
{ 'TEXT', or 'snd ' data}
previewFormat: FormatType; {type of preview}
container: EditionContainerSpec;
{edition chosen}
END;
Field descriptions
canceled The NewPublisherDialog function returns in this field a value that indicates whether the user canceled the dialog box. The function returns TRUE in the canceled field if the user canceled the dialog box. The function returns FALSE in this field if the user clicked the Publish button and returns in the container field the edition container for the new publisher.
replacing The NewPublisherDialog function returns TRUE in the replacing field if the user chose an existing filename from the list of available editions and confirmed this replacement. If the value of the replacing field is TRUE, do not call the CreateEditionContainerFile function. If the value of this field and the canceled field is FALSE, you can call CreateEditionContainerFile to create a new edition container.
usePart A value that must be set to FALSE before calling the NewPublisherDialog function.
preview A handle to 'prvw', 'PICT', 'TEXT', or 'snd ' data. The NewPublisherDialog function displays this data in the preview area of the dialog box.
previewFormat A value that indicates which type of data the handle in the preview field references.
container An edition container record that specifies the volume reference number, directory ID, and filename to use as the default edition to publish the data to. The NewPublisherDialog function returns in this field the edition container that the user selected.
DESCRIPTION
The NewPublisherDialog function displays the new publisher dialog box on the user’s screen. The NewPublisherDialog function (which is based on the CustomPutFile procedure described in the chapter “Standard File Package” in Inside Macintosh: Files) switches to the volume reference number and directory ID specified by the edition container, sets the editable text item to the filename specified by the edition container, and displays a preview of the publisher data in the new publisher dialog box. The NewPublisherDialog function handles all user interaction until the user clicks the Cancel or Publish button.
You should deallocate the handle referenced by the preview field to free up memory.
RESULT CODESnoErr 0 No error
editionMgrInitErr –450 Manager not initialized or could not load package
badSubPartErr –454 Bad edition container spec
SEE ALSO
For an illustration of the new publisher dialog box, see Figure 2-11 on page 2-29. For an example of the use of NewPublisherDialog, see Listing 2-4 beginning on page 2-33. For a description of the edition container record, see page 2-71.
SectionOptionsDialog
Use the SectionOptionsDialog function to display the publisher options and subscriber options dialog boxes on the user’s screen.
FUNCTION SectionOptionsDialog
(VAR reply: SectionOptionsReply): OSErr;
reply The reply parameter contains a section options reply record. You specify a handle to the publisher’s or subscriber’s section record in the sectionH field of this record. The SectionOptionsDialog function returns information concerning the user’s actions in the canceled, changed, and action fields.
TYPE SectionOptionsReply =
RECORD
canceled: Boolean; {user canceled dialog box}
changed: Boolean; {changed the section record}
sectionH: SectionHandle; {handle to the specified }
{ section record}
action: ResType; {action codes}
END;
Field descriptions
canceled The SectionOptionsDialog function returns in this field a value that indicates whether the user canceled the dialog box. The function returns TRUE in the canceled field if the user canceled the dialog box. Otherwise, the function returns FALSE in this field.
changed The SectionOptionsDialog function returns TRUE in this field if the user changed the section record. For example, the update mode may have changed. Otherwise, the function returns FALSE in this field.
sectionH A handle to the section record for the section the user selected.
action The SectionOptionsDialog function returns in this field the code for one of five user actions: action code 'read' for user selection of the Get Edition Now button, action code 'writ' for user selection of the Send Edition Now button, action code 'goto' for user selection of the Open Publisher button, action code 'cncl' for user selection of the Cancel Publisher or Cancel Subscriber button, or action code ' ' ($20202020) for user selection of the OK button.
DESCRIPTION
The SectionOptionsDialog function displays the appropriate options dialog box for the specified section record. The function displays information about the subscriber or publisher, such as its latest edition and current update mode setting, and allows the user to perform various actions. The SectionOptionsDialog function handles all user interaction until the user selects a button. The function returns the user’s action in the action field of the reply parameter; your application should then perform the corresponding action.
RESULT CODESnoErr 0 No error
memFullErr –108 Memory full
SEE ALSO
For illustrations of the section options dialog box, see Figure 2-13 through Figure 2-16 beginning on page 2-43. For an example of the use of SectionOptionsDialog, see Listing 2-8 beginning on page 2-46. For a description of the section record, see page 2-72.
The NewSubscriberExpDialog, NewPublisherExpDialog, and SectionOptionsExpDialog functions are the same as the simple dialog functions but have five additional parameters. These additional parameters allow you to add items to the bottom of the dialog boxes, apply alternate mapping of events to item hits, apply alternate meanings to the item hits, and choose the location of the dialog boxes.
FUNCTION NewSubscriberExpDialog
(VAR reply: NewSubscriberReply; where: Point;
expansionDITLresID: Integer;
dlgHook: ExpDlgHookProcPtr;
filterProc: ExpModalFilterProcPtr;
yourDataPtr: UNIV Ptr): OSErr;
FUNCTION NewPublisherExpDialog
(VAR reply: NewPublisherReply; where: Point;
expansionDITLresID: Integer;
dlgHook: ExpDlgHookProcPtr;
filterProc: ExpModalFilterProcPtr;
yourDataPtr: UNIV Ptr): OSErr;
FUNCTION SectionOptionsExpDialog
(VAR reply: SectionOptionsReply; where: Point;
expansionDITLresID: Integer;
dlgHook: ExpDlgHookProcPtr;
filterProc: ExpModalFilterProcPtr;
yourDataPtr: UNIV Ptr): OSErr;
reply A new subscriber reply, new publisher reply, or section options reply record. You specify information in the fields of this record just as you do in the the corresponding fields of records used by NewSubscriberDialog, NewPublisherDialog, and SectionOptionsDialog.
where A point that specifies a location on the screen where the function displays the dialog box. You can automatically center the dialog box by passing (–1, –1) in the where parameter.
expansionDITLresID
A value of 0 or a valid item list ('DITL') resource ID. This integer is the ID of a dialog item list whose items are appended to the end of the standard dialog item list. The dialog items keep their relative positions, but they are moved as a group to the bottom of the dialog box.
dlgHook A pointer to an expandable dialog hook function or NIL. An expandable dialog hook function is similar to a dialog hook function except that an expandable dialog hook function accepts an additional parameter. The NewSubscriberExpDialog, NewPublisherExpDialog, and SectionOptionsExpDialog functions call your expandable dialog hook function after each call to the ModalDialog procedure. The expandable dialog hook function should take the appropriate action, such as filling in a checkbox. The itemOffset parameter to the expandable dialog hook function is the number of items in the item list before your expansion dialog items. You need to subtract the item offset from the item hit to get the relative item number in the expansion item list. The expandable dialog hook function should return as its function result the absolute item number.
filterProc
A pointer to an expandable modal-dialog filter function or NIL. An expandable modal-dialog filter function is similar to a modal-dialog filter function or event filter function except that an expandable modal-dialog filter function accepts two extra parameters. The ModalDialog procedure calls the expandable modal-dialog filter function you provide in this parameter. An expandable modal-dialog filter function allows you to map real events (such as a mouse-down event) to an item hit (such as clicking a Cancel button). For instance, you may want to map a keyboard equivalent to an item hit.
yourDataPtr
Reserved for your use. It is passed back to your hook and event filter function. This parameter does not have to be of type Ptr—it can be any 32-bit quantity that you want. In Pascal, you can pass yourDataPtr in register A6, and declare your dialog hook and event filter as local functions without the last parameter. The stack frame is set up properly for these functions to access their parent local variables.
DESCRIPTION
The NewPublisherExpDialog, NewSubscriberExpDialog, and SectionOptionsExpDialog functions display the appropriate dialog box, handle user interaction, and call any functions you have provided in the dlgHook and filterProc parameters.
For the NewPublisherExpDialog and NewSubscriberExpDialog functions, all the pseudo-items for the Standard File Package such as hookFirstCall(–1), hookNullEvent(100), hookRebuildList(101), and hookLastCall(–2) can be used, as well as hookRedrawPreview(150).
For the SectionOptionsExpDialog function, the only valid pseudo-items are hookFirstCall(–1), hookNullEvent(100), hookLastCall(–2), emHookRedrawPreview(150), emHookCancelSection(160), emHookGoToPublisher(161), emHookGetEditionNow(162), emHookSendEditionNow(162), emHookManualUpdateMode(163), and emHookAutoUpdateMode(164).
If you provide an expandable dialog hook function, it must contain the following parameters:
FUNCTION MyExpDlgHook (itemOffset: Integer; itemHit: Integer;
theDialog: DialogPtr;
yourDataPtr: Ptr): Integer;
If you provide an expandable modal-dialog filter function, it must contain the following parameters.
FUNCTION MyExpModalFilter (theDialog: DialogPtr;
VAR theEvent: EventRecord;
itemOffset: Integer;
VAR itemHit: Integer;
yourDataPtr: Ptr): Boolean;
SEE ALSO
See the chapter “Dialog Manager” in Inside Macintosh: Macintosh Toolbox Essentials for additional information on item lists. See the chapter “Standard File Package” in Inside Macintosh: Files for information on dialog hook and modal-dialog filter functions.
Locating a Publisher and Edition From a Subscriber
The GetEditionInfo function returns information about a section’s edition such as its location, last modification date, creator, and type.
Once you locate a section’s edition, you can use the GoToPublisherSection function to find the document containing the publisher.
GetEditionInfo
Use the GetEditionInfo function to obtain information about a section’s edition, such as its location, last modification date, creator, and type.
FUNCTION GetEditionInfo
(sectionH: SectionHandle;
VAR editionInfo: EditionInfoRecord): OSErr;
sectionH A handle to the section record for a given section.
editionInfo
An edition information record. The GetEditionInfo function returns the public information contained in the section’s control block.
DESCRIPTION
The Edition Manager ensures that the existing edition name corresponds to the Finder’s existing edition name. If the controlBlock field of the section record is set to NIL or the edition cannot be located, the GetEditionInfo function returns an fnfErr result code.
The GetEditionInfo function returns information about the section’s edition in a data structure of type EditionInfoRecord.
TYPE EditionInfoRecord =
RECORD
crDate: TimeStamp; {date edition container }
{ was created}
mdDate: TimeStamp; {date of last change}
fdCreator: OSType; {file creator}
fdType: OSType; {file type}
container: EditionContainerSpec; {the edition}
END;
Field descriptions
crDate The creation date of the edition.
mdDate The modification date of the edition.
fdCreator The creator of the edition file.
fdType The file type of the edition file.
container An edition container record, which specifies the volume reference number, directory ID, filename, script, and part number for the edition.
RESULT CODESnoErr 0 No error
fnfErr –43 Not registered or file moved
editionMgrInitErr –450 Manager not initialized
SEE ALSO
For an example of the use of GetEditionInfo, see Listing 2-8 beginning on page 2-46. For another use of this function, see “Canceling Sections Within Documents” beginning on page 2-48. For a description of the edition container record, see page 2-71.
GoToPublisherSection
When the user wants to locate the publisher for a particular subscriber (by clicking Open Publisher in the subscriber options dialog box), the SectionOptionsDialog function returns the action code 'goto' in the action field of the section options reply record. When you receive this action code, you should open the document containing the publisher.
First, use the GetEditionInfo function to find the edition container. Then use the GoToPublisherSection function to open the document containing the publisher.
FUNCTION GoToPublisherSection
(container: EditionContainerSpec): OSErr;
container An edition container record, which specifies volume reference number, directory ID, and filename of the subscriber’s edition. You obtain the edition container by calling the GetEditionInfo function.
DESCRIPTION
The GoToPublisherSection function resolves the alias in the edition to find the document containing its publisher. In general, this function internally uses the GetStandardFormats function to get the alias to the publisher document and then resolves the alias. It next sends the Finder an Apple event to open the document (which launches its application if necessary) and, after the publisher is registered, sends a Section Scroll event to the publisher.
As an optimization, if there is a registered publisher, the GoToPublisherSection function simply sends a Section Scroll event to the publisher.
If the edition does not contain an alias and there are no registered publishers, then the GoToPublisherSection function sends an Open Documents event to open the edition to the creating application.
If the edition container is not an edition file (as is the case when you are using bottlenecks to subscribe to non-edition files), the GoToPublisherSection function sends the Finder an Apple event to open that file.
RESULT CODESnoErr 0 No error
fnfErr –43 File not found
editionMgrInitErr –450 Manager not initialized
badSubPartErr –454 Invalid edition container
SEE ALSO
For illustrations of the section options dialog box for subscribers, see Figure 2-15 on page 2-44 and Figure 2-16 on page 2-45. For an example of responding to the action code 'goto', see Listing 2-8 beginning on page 2-46. For a description of the edition container record, see page 2-71.
Edition Container Formats
The Edition Manager calls the GetStandardFormats function to get the alias used in the GoToPublisherSection function and to get the preview shown in the subscriber dialog box. You probably do not need to call this function directly.
GetStandardFormats
You probably do not need to call the GetStandardFormats function directly because the Edition Manager calls this function.
FUNCTION GetStandardFormats
(container: EditionContainerSpec;
VAR previewFormat: FormatType;
preview, publisherAlias, formats: Handle): OSErr;
container An edition container record that specifies the edition volume reference number, directory ID, filename, and part.
previewFormat
The GetStandardFormats function returns in this parameter a handle to the first format of the requested format type that it finds in the edition.
preview A format type. The GetStandardFormats function looks for a format of the type specified in this parameter and returns in this parameter the format type of the first format that it finds. The function tries to find one of four formats: 'prvw', 'PICT', 'TEXT', or 'snd '.
publisherAlias
The publisherAlias parameter reads the format kPublisherDocAliasFormat ('alis').
formats The formats parameter reads the virtual format kFormatListFormat ('fmts').
DESCRIPTION
You should pass in valid handles for the formats that you want and NIL for the formats that you don’t want. The handles are resized to the size of the data.
If one of the requested formats cannot be found, GetStandardFormats returns a noTypeErr result code.
RESULT CODESnoErr 0 No error
noTypeErr –102 Edition container not found
editionMgrInitErr –450 Manager not initialized
Reading and Writing Non-Edition Files
The Edition Manager never opens or closes an edition container directly—it calls the current edition opener. See “Subscribing to Non-Edition Files” beginning on page 2-62 for additional information.
To override the standard opener function, create an opener function that contains the following parameters:
FUNCTION MyOpener (selector: EditionOpenerVerb;
VAR PB: EditionOpenerParamBlock): OSErr;
When this function is called by the Edition Manager, the selector parameter is set to one of the edition opener verbs (eoOpen, eoClose, eoOpenNew, eoCloseNew, eoCanSubscribe). The PB parameter contains an edition opener parameter block record.
Use the GetEditionOpenerProc function to locate the current edition opener and use the SetEditionOpenerProc function to provide your own edition opener.
Use the CallEditionOpenerProc function to call an edition opener and use the CallFormatIOProc function to call a format I/O function.
GetEditionOpenerProc
Use the GetEditionOpenerProc function to locate the current edition opener.
FUNCTION GetEditionOpenerProc
(VAR opener: EditionOpenerProcPtr): OSErr;
opener The GetEditionOpenerProc function returns a pointer to the current edition opener function in this parameter.
SetEditionOpenerProc
Use the SetEditionOpenerProc function to provide your own edition opener.
FUNCTION SetEditionOpenerProc
(opener: EditionOpenerProcPtr): OSErr;
opener A pointer to the edition opener function that you are providing.
CallEditionOpenerProc
Use the CallEditionOpenerProc function to call an edition opener.
FUNCTION CallEditionOpenerProc
(selector: EditionOpenerVerb;
VAR PB: EditionOpenerParamBlock;
routine: EditionOpenerProcPtr): OSErr;
selector An edition opener verb. When the CallEditionOpenerProc function is called by the Edition Manager, the selector parameter is set to one of the edition opener verbs (eoOpen, eoClose, eoOpenNew, eoCloseNew, eoCanSubscribe).
PB An edition opener parameter block.
routine A pointer to an edition opener function.
DESCRIPTION
The Edition Manager calls an edition opener function whenever it needs to open or close an edition. The Edition Manager passes an edition opener parameter block as one of the parameters to an edition opener function. The edition opener parameter block is defined by this structure:
TYPE EditionOpenerParamBlock =
RECORD
info: EditionInfoRecord; {edition container to }
{ be subscribed to}
sectionH: SectionHandle; {publisher or }
{ subscriber }
{ requesting open}
document: FSSpecPtr; {document passed}
fdCreator: OSType; {Finder creator type}
ioRefNum: LongInt; {reference number}
ioProc: FormatIOProcPtr; {routine to read }
{ formats}
success: Boolean; {reading or writing }
{ was successful}
formatsMask: SignedByte; {formats required to }
{ subscribe}
END;
To override the standard reading and writing functions, you should create an I/O function that contains the following parameters.
FUNCTION MyIO (selector: FormatIOVerb;
VAR PB: FormatIOParamBlock): OSErr;
Set the selector parameter to one of the format I/O verbs (ioHasFormat, ioReadFormat, ioNewFormat, ioWriteFormat). The PB parameter contains a format I/O parameter block record.
SEE ALSO
See “Calling an Edition Opener” beginning on page 2-64 for additional information.
CallFormatIOProc
Use the CallFormatIOProc function to call a format I/O function.
FUNCTION CallFormatIOProc (selector: FormatIOVerb;
VAR PB:FormatIOParamBlock;
routine: FormatIOProcPtr): OSErr;
selector A format I/O verb (ioHasFormat, ioReadFormat, ioNewFormat, ioWriteFormat).
PB A format I/O parameter block record.
routine A pointer to a format I/O function.
DESCRIPTION
The Edition Manager calls a format I/O function whenever it needs to read from or write to an edition. The Edition Manager passes a format I/O parameter block as one of the parameters to a format I/O procedure. The format I/O parameter block is defined by this structure:
See “Calling a Format I/O Function” beginning on page 2-68 for additional information.
Application-Defined Routines
Your application can provide an edition opener function, format I/O function, expandable dialog hook function, and expandable modal-dialog filter function. For the routine declarations of the edition opener and format I/O functions, see “Reading and Writing Non-Edition Files” beginning on page 2-102. For the routine declarations of the expandable dialog hook and expandable modal-dialog filter functions, see the description of NewSubscriberExpDialog, NewPublisherExpDialog, and SectionOptionsExpDialog beginning on page 2-96.
Summary of the Edition Manager
Pascal Summary
Constants
CONST
{resource types}
rSectionType = 'sect'; {resource type for a }
{ section}
{section types}
stSubscriber = $01; {subscriber section type}
stPublisher = $0A; {publisher section type}
{update modes}
sumAutomatic = 0; {subscriber receives new }
{ editions automatically}
sumManual = 1; {subscriber receives new }
{ editions manually}
pumOnSave = 0; {publisher sends new }
{ editions on save}
pumManual = 1; {publisher does not send }
{ new editions until user }
{ request}
{edition container subpart number}
kPartsNotUsed = 0; {edition is the whole file}
kPartNumberUnknown = -1; {not used in version 7.0}
{preview size}
kPreviewWidth = 120; {preview width}
kPreviewHeight = 120; {preview height}
{special formats}
kPublisherDocAliasFormat = 'alis'; {alias record from the }
userCanceledErr –128 User clicked Cancel in dialog box
editionMgrInitErr –450 Manager not initialized or could not load package
badSectionErr –451 Not a valid section type
notRegisteredSectionErr –452 Not registered
badSubPartErr –454 Bad edition container spec or invalid edition container
multiplePublisherWrn –460 Already is a publisher
containerNotFoundWrn –461 Alias was not resolved
notThePublisherWrn –463 Not the publisher
Listing 3-0
Table 3-0
Introduction to Apple Events
Contents
About Apple Events3-3
Apple Events and Apple Event Objects3-6
Apple Event Attributes and Parameters3-7
Apple Event Attributes3-8
Apple Event Parameters3-9
Interpreting Apple Event Attributes and Parameters3-10
Data Structures Within Apple Events3-12
Descriptor Records3-12
Keyword-Specified Descriptor Records3-15
Descriptor Lists3-16
Responding to Apple Events3-20
Accepting and Processing Apple Events3-20
About Apple Event Handlers3-23
Extracting and Checking Data3-23
Interacting With the User3-25
Performing the Requested Action and Returning a Result3-25
Creating and Sending Apple Events3-28
Creating an Apple Event Record3-29
Adding Apple Event Attributes and Parameters3-29
Sending an Apple Event and Handling the Reply3-30
Working With Object Specifier Records3-32
Data Structures Within an Object Specifier Record3-34
The Classification of Apple Event Objects3-39
Object Classes3-39
Properties and Elements3-42
Finding Apple Event Objects3-46
About the Apple Event Manager3-48
Supporting Apple Events as a Server Application3-48
Supporting Apple Events as a Client Application3-49
Supporting Apple Event Objects3-49
Supporting Apple Event Recording3-50
Introduction to Apple Events
This chapter introduces Apple events and the Apple Event Manager. Later chapters describe how your application can use the Apple Event Manager to respond to and send Apple events, locate Apple event objects, and record Apple events.
The interapplication communication (IAC) architecture for Macintosh computers consists of five parts: the Edition Manager, the Open Scripting Architecture (OSA), the Apple Event Manager, the Event Manager, and the Program-to-Program Communications (PPC) Toolbox. The chapter “Introduction to Interapplication Communication” in this book provides an overview of the relationships among these parts.
The Apple Event Registry: Standard Suites defines both the actions performed by the standard Apple events, or “verbs,” and the standard Apple event object classes, which can be used to create “noun phrases” describing objects on which Apple events act. If your application uses the Apple Event Manager to respond to some of these standard Apple events, you can make it scriptable—that is, capable of responding to scripts written in a scripting language such as AppleScript. In addition, your application can use the Apple Event Manager to create and send Apple events and to allow user actions in your application to be recorded as Apple events.
Before you use this chapter or any of the other chapters about the Apple Event Manager, you should be familiar with the chapters “Event Manager” in Inside Macintosh: Macintosh Toolbox Essentials and “Process Manager” in Inside Macintosh: Processes.
This chapter begins by describing Apple events and some of the data structures they contain. The rest of the chapter introduces the use of the Apple Event Manager to
n respond to Apple events
n send Apple events to request services or information
n work with object specifier records
n classify Apple event objects
n locate Apple event objects
Finally, this chapter summarizes the tasks you can perform with the Apple Event Manager and explains where to locate information you need to perform those tasks.
About Apple Events
An Apple event is a high-level event that conforms to the Apple Event Interprocess Messaging Protocol. The Apple Event Manager uses the services of the Event Manager to send Apple events between applications on the same computer, between applications on remote computers, or from an application to itself.
Applications typically use Apple events to request services and information from other applications or to provide services and information in response to such requests. Communication between two applications that support Apple events is initiated by a client application, which sends an Apple event to request a service or information. The application providing the service or the requested information is called a server application. The client and server applications can reside on the same local computer or on remote computers connected to a network. An application can also send Apple events to itself, thus acting as both client and server.
Figure 3-1 shows a common Apple event, the Open Documents event. The Finder is the client; it requests that the SurfWriter application open the documents named “Dec. Invoice” and “Nov. Invoice.” The SurfWriter application responds to the Finder’s request by opening windows for the specified documents.
Figure 3-1 An Open Documents event
The Finder is considered the client application for the Open Documents event shown in Figure 3-1 because the Finder initiates the request for a service. The Finder can also be considered the source application for the same Open Documents event. A source application for an Apple event is one that sends an Apple event to another application or to itself. Similarly, the SurfWriter application can be described as either the server application or the target application for the Open Documents event shown in Figure 3-1. A target application for an Apple event is the one addressed to receive the Apple event. The terms client application and source application are not always synonymous, nor are the terms server application and target application. Typically, an Apple event client application sends an Apple event requesting a service to an Apple event server application;
in this case, the server application is the target application for the Apple event. A server application may return information to the client in a reply Apple event—in which case, the client application is the target application for the reply.
To perform the requested service—that is, to open the specified documents—the SurfWriter application shown in Figure 3-1 first uses the Apple Event Manager to identify the event (the Open Documents event) and to dispatch the event to SurfWriter’s handler for that Apple event. An Apple event handler is an application-defined function that extracts pertinent data from an Apple event, performs the requested action, and (usually) returns a result. In this case, SurfWriter’s Open Documents event handler examines the Apple event to determine which documents to open (Dec. Invoice and Nov. Invoice), then opens them as requested.
To identify Apple events and respond appropriately, every application can rely on a vocabulary of standard Apple events that developers and Apple have established for all applications to use. These events are defined in the Apple Event Registry: Standard Suites. The standard suites, or groups of related Apple events that are usually implemented together, include the Required suite, the Core suite, and functional-area suites such as the Text suite and the Database suite. To function as a server application, your application should be able to respond to all the Apple events in the Required suite and any of those in the Core and functional-area suites that it is likely to receive. For example, most word-processing applications should be capable of responding to the Apple events in the Text suite, and most database applications should be capable of responding to those in the Database suite.
If necessary, you can extend the definitions of the standard Apple events to match specific capabilities of your application. You can also define your own custom Apple events; however, before defining custom events, you should check with the Apple Event Registrar to find out whether you can adapt existing Apple event definitions or definitions still under development to the needs of your application.
By supporting the standard Apple events in your application, you ensure that your application can communicate effectively with other applications that also support them. Instead of supporting many different custom events for a limited number of applications, you can support a relatively small number of standard Apple events that can be used by any number of applications.
You can begin supporting Apple events by making your application a reliable server application: first for the required Apple events, then for the core and functional-area Apple events as appropriate. Once your application can respond to the appropriate standard Apple events, you can make it scriptable, or capable of responding to instructions written in a system-wide scripting language such as AppleScript. If necessary, your application can also send Apple events to itself or to other applications.
“About the Apple Event Manager,” which begins on page 3-48, provides more information about the steps you need to take to support Apple events in your application.
The next section, “Apple Events and Apple Event Objects,” describes how Apple events can describe data and other items within an application or its documents. Subsequent sections describe the basic organization of Apple events and the data structures from which they are constructed.
Apple Events and Apple Event Objects
The Open Documents event shown in Figure 3-1, like the other three required events, specifies an action and the applications or documents to which that action applies. The Apple Event Registry: Standard Suites provides a vocabulary of actions for use by all applications. In addition to a vocabulary of actions, effective communication between applications requires a method of referring to windows, data (such as words or graphic elements), files, folders, volumes, zones, and other discrete items on which actions can be performed. The Apple Event Manager includes routines that allow any application to construct or interpret “noun phrases” that describe the objects on which Apple events act.
Most of the Apple event definitions in the Apple Event Registry: Standard Suites include definitions of Apple event object classes, which are simply names for objects that can be acted upon by each kind of Apple event. An Apple event object is any distinct item supported by an application that can be described within an Apple event. Apple event objects can be anything that an application can locate on the basis of such a description, including items that a user can differentiate and manipulate while using an application, such as words, paragraphs, shapes, windows, or style formats.
The definition for each Apple event object class in the Apple Event Registry: Standard Suites determines only how that kind of Apple event object should be described within an Apple event, not how it should be represented internally by an individual application. You do not have to write your application in an object-oriented programming language to support Apple event objects. Instead, you need to organize your application so that it can interpret a request for specific Apple event objects, locate the objects, and perform the requested action on them.
Figure 3-2 shows a common Apple event, the Get Data event from the Core suite. In this example, the SurfCharter application is the client application; it requests data contained in a specific table in a SurfWriter document. To obtain the data it wants, the SurfCharter application must include a description of the data in the Get Data event it sends to SurfWriter. This description identifies the requested data as an Apple event object called a table. The table is named “Summary of Sales” and is located in a document named “Sales Report.”
The SurfWriter application’s Get Data handler extracts information about the request, locates the specified table, and returns a result. The Apple Event Manager provides a reply Apple event to which the SurfWriter application adds the requested information in the form requested by the Get Data event. The Apple Event Manager sends the reply event back to the SurfCharter application, which can use the requested data in whatever way is appropriate—in this case, displaying it as a pie chart.
Figure 3-2 A Get Data event
Apple Event Attributes and Parameters
When an application creates and sends an Apple event, the Apple Event Manager uses arguments passed to Apple Event Manager routines to construct the data structures that make up the Apple event. An Apple event consists of attributes (which identify the Apple event and denote its task) and, often, parameters (which contain information to be used by the target application).
An Apple event attribute is a record that identifies the event class, event ID, target application, or some other characteristic of an Apple event. Taken together, the attributes of an Apple event denote the task to be performed on any data specified in the Apple event’s parameters. A client application can use Apple Event Manager routines to add attributes to an Apple event. After receiving an Apple event, a server application can use Apple Event Manager routines to extract and examine its attributes.
An Apple event parameter is a record containing data that the target application uses. Unlike Apple event attributes (which contain information that can be used by both the Apple Event Manager and the target application), Apple event parameters contain data used only by the target application. For example, the Apple Event Manager uses the event class and event ID attributes to identify the server application’s handler for a specific Apple event, and the server application must have a handler to process the event identified by those attributes. By comparison, the list of documents contained in a parameter to an Open Documents event is used only by the server application. As with attributes, a client application can use Apple Event Manager routines to add parameters to an Apple event, and a server application can use Apple Event Manager routines to extract and examine the parameters of an Apple event it has received.
Note that Apple event parameters are different from the parameters of Apple Event Manager functions. Apple event parameters are records used by the Apple Event Manager; function parameters are arguments you pass to the function or that the function returns to you. You can specify both Apple event parameters and Apple event attributes in parameters to Apple Event Manager functions. For example, the AEGetParamPtr function uses a buffer to return the data contained in an Apple event parameter. You can specify the Apple event parameter whose data you want in one of the parameters of the AEGetParamPtr function.
Apple Event Attributes
Apple events are identified by their event class and event ID attributes. The event class is the attribute that identifies a group of related Apple events. The event class appears in the message field of the event record for an Apple event. For example, the four required Apple events have the value 'aevt' in the message fields of their event records. The value 'aevt' can also be represented by the kCoreEventClass constant. Several event classes are shown here:
Event class Value Description
kCoreEventClass 'aevt' A required Apple event
kAECoreSuite 'core' A core Apple event
kAEFinderEvents 'FNDR' An event that the Finder accepts
kSectionEventMsgClass 'sect' An event sent by the Edition Manager
The event ID is the attribute that identifies the particular Apple event within its event class. In conjunction with the event class, the event ID uniquely identifies the Apple event and communicates what action the Apple event should perform. (The event IDs appear in the where field of the event record for an Apple event. For more information about event records, see the chapter “Event Manager” in Inside Macintosh: Macintosh Toolbox Essentials.) For example, the event ID of an Open Documents event has the value 'odoc' (which can also be represented by the kAEOpenDocuments constant). The kCoreEventClass constant in combination with the kAEOpenDocuments constant identifies the Open Documents event to the Apple Event Manager.
Here are the event IDs for the four required Apple events:
Event ID Value Description
kAEOpenApplication 'oapp' Perform tasks required when a user opens your application without opening or printing any documents
kAEOpenDocuments 'odoc' Open documents
kAEPrintDocuments 'pdoc' Print documents
kAEQuitApplication 'quit' Quit your application
In addition to the event class and event ID attributes, every Apple event must include an attribute that specifies the target application’s address. Remember that the target application is the one addressed to receive the Apple event. Your application can send an Apple event to itself or to another application (on the same computer or on a remote computer connected to the network).
Every Apple event must include event class, event ID, and target address attributes. Some Apple events can include other attributes; see “Keyword-Specified Descriptor Records,” which begins on page 3-15, for a complete list.
Apple Event Parameters
As with attributes, there are various kinds of Apple event parameters. A direct parameter usually specifies the data to be acted upon by the target application. For example, the direct parameter of the Print Documents event contains a list of documents. Some Apple events also take additional parameters, which the target application uses in addition to the data specified in the direct parameter. Thus, an Apple event for arithmetic operations might include additional parameters that specify operands in an equation.
The Apple Event Registry: Standard Suites describes all parameters as either required or optional. A required parameter is one that must be present for the target application to carry out the task denoted by the Apple event. An optional parameter is a supplemental Apple Event parameter that also can be used to specify data to the target application. Optional parameters need not be included in an Apple event; default values for optional parameters are part of the event definition. The target application that handles the event must supply default values if the optional parameters are omitted.
Direct parameters are usually defined as required parameters in the Apple Event Registry: Standard Suites; additional parameters may be defined as either required or optional. However, the Apple Event Manager does not enforce the definitions of required and optional events. Instead, the source application specifies, when it sends the event, which Apple event parameters the target can treat as if they were optional.
For more information about optional parameters, see “Specifying Optional Parameters for an Apple Event,” which begins on page 5-7.
Interpreting Apple Event Attributes and Parameters
Figure 3-3 shows the major Apple event attributes and direct parameter for the Open Documents event introduced in Figure 3-1.
Figure 3-3 Major attributes and direct parameter of an Open Documents event
When the SurfWriter application receives any high-level event, it calls the AEProcessAppleEvent function to process the event. For an Apple event such as the Open Documents event shown in Figure 3-3, the AEProcessAppleEvent function uses the event class and event ID attributes to dispatch the event to the SurfWriter application’s Open Documents handler. In response, the Open Documents handler opens the documents specified in the direct parameter.
The definition of a given Apple event in the Apple Event Registry: Standard Suites suggests how the source application can organize the data in the Apple event’s parameters and how the target application interprets that data. The data in an Apple event parameter may use standard or private data types and may include a description of an Apple event object. Each Apple event handler provided by an application should be written with the format of the expected data in mind.
Apple events can use standard data types, such as strings of text, long integers, Boolean values, and alias records, for the corresponding data in Apple event parameters. For example, the Get Data event can contain an optional parameter specifying the form in which the requested data should be returned. This optional parameter always consists of a list of four-character codes denoting desired descriptor types in order of preference. Apple events can also use special data types defined by the Apple Event Manager.
Apple event parameters often contain descriptions of Apple event objects. These descriptions make use of a standard classification scheme summarized in “The Classification of Apple Event Objects,” which begins on page 3-39.
For example, every Get Data event includes a required parameter that describes the Apple event object containing the data requested by the client application. Thus, one application can send a Get Data event to another application, requesting, for instance, one paragraph of a document, the first and last paragraphs of a document, all pictures in the document, all paragraphs containing the word “sales,” or pages 10 through 12 of the document.
Figure 3-4 shows the Apple event attributes and direct parameter for the Get Data event introduced in Figure 3-2. The direct parameter for the Get Data event sent by the SurfCharter application describes the requested Apple event object as a table called “Summary of Sales” in the document “Sales Report.” Both the table and the document are Apple event objects. The description of an Apple event object always includes a description of its location. In most cases, Apple event objects are located inside other Apple event objects.
Figure 3-4 Major attributes and direct parameter of a Get Data event
To process the information in the Get Data event, the SurfWriter application calls the AEProcessAppleEvent function. The AEProcessAppleEvent function uses the event class and event ID attributes to dispatch the event to the SurfWriter application’s handler for the Get Data Apple event. The SurfWriter application responds to the Get Data event by resolving the description of the Apple event object—that is, by using the AEResolve function, other Apple Event Manager routines, and its own application-defined functions to locate the table named “Summary of Sales.” After locating the table, SurfWriter adds a copy of the table’s data to the reply event, which the Apple Event Manager then sends to the SurfCharter application. The SurfCharter application then displays the data in its active window.
The next section, “Data Structures Within Apple Events,” describes the data structures the Apple Event Manager uses for Apple event attributes and parameters.
Data Structures Within Apple Events
The Apple Event Manager constructs its own internal data structures to contain the information in an Apple event. Neither the sender nor the receiver of an Apple event should manipulate data directly after it has been added to an Apple event; each should rely on Apple Event Manager functions to do so.
This section describes the most important data structures used by the Apple event Manager to construct Apple events. The first structure described is the descriptor record, a data structure of type AEDesc. Applications may access the data in an individual descriptor record directly if it is not part of another Apple Event Manager data structure.
In some cases it is convenient for the Apple Event Manager to describe descriptor records by data types that indicate their contents; thus, it also defines data structures such as type AEAddressDesc, AEDescList, and AERecord, which are descriptor records used to hold addresses, lists of other descriptor records, and Apple event parameters, respectively. These and most of the other data structures described in this section are formally defined as data structures of type AEDesc; they differ only in the purposes for which they are used.
Descriptor Records
Descriptor records are the building blocks used by the Apple Event Manager to construct Apple event attributes and parameters. A descriptor record is a data structure of type AEDesc; it consists of a handle to data and a descriptor type that identifies the type of the data to which the handle refers.
TYPE AEDesc =
RECORD {descriptor record}
descriptorType: DescType; {type of data}
dataHandle: Handle ; {handle to data}
END;
If a descriptor record exists separately from other Apple Event Manager data structures, it is possible to retrieve the data associated with its handle by dereferencing the handle twice. After a descriptor record has been added to any other Apple Event Manager data structure, you must use Apple Event Manager routines to extract data from the descriptor record.
The descriptor type is a structure of type DescType, which in turn is of data type ResType—that is, a four-character code. Constants are usually used in place of these four-character codes when referring to descriptor types. Descriptor types represent various data types. Here are some of the major descriptor type constants, their values, and the kinds of data they identify.
Descriptor type Value Description of data
typeBoolean 'bool' 1-byte Boolean value
typeChar 'TEXT' Unterminated string
typeLongInteger 'long' 32-bit integer
typeShortInteger 'shor' 16-bit integer
typeMagnitude 'magn' Unsigned 32-bit integer
typeAEList 'list' List of descriptor records
typeAERecord 'reco' List of keyword-specified descriptor records
typeAppleEvent 'aevt' Apple event record
typeEnumerated 'enum' Enumerated data
typeType 'type' Four-character code
typeFSS 'fss ' File system specification
typeKeyword 'keyw' Apple event keyword
typeNull 'null' Nonexistent data (handle whose value is NIL)
For a complete list of the basic descriptor types used by the Apple Event Manager, see Table 4-2 on page 4-57.
Figure 3-5 illustrates the logical arrangement of a descriptor record with a descriptor type of typeChar, which specifies that the data handle refers to an unterminated string (in this case, the text “Summary of Sales”).
Figure 3-5 A descriptor record whose data handle refers to an unterminated string
Figure 3-6 illustrates the logical arrangement of a descriptor record with a descriptor type of typeType, which specifies that the data handle refers to a four-character code (in this case the constant kCoreEventClass, whose value is 'aevt'). This descriptor record can be used in an Apple event attribute that identifies the event class for any Apple event in the Core suite.
Figure 3-6 A descriptor record whose data handle refers to event class data
Every Apple event includes an attribute specifying the address of the target application. A descriptor record that contains an application’s address is called an address descriptor record.
TYPE AEAddressDesc = AEDesc; {address descriptor record}
The address in an address descriptor record can be specified as one of these four basic types (or as any other descriptor type you define that can be coerced to one of these types):
Descriptor type Value Description
typeApplSignature 'sign' Application signature
typeSessionID 'ssid' Session reference number
typeTargetID 'targ' Target ID record
typeProcessSerialNumber 'psn ' Process serial number
Like several of the other data structures defined by the Apple Event Manager for use in Apple event attributes and Apple event parameters, an address descriptor record is identical to a descriptor record of data type AEDesc; the only difference is that the data for an address descriptor record must always consist of an application’s address.
Keyword-Specified Descriptor Records
After the Apple Event Manager has assembled the necessary descriptor records as the attributes and parameters of an Apple event, your application cannot examine the contents of the Apple event directly. Instead, your application must use Apple Event Manager routines to request each attribute and parameter by keyword. Keywords are arbitrary names used by the Apple Event Manager to keep track of various descriptor records. The AEKeyword data type is defined as a four-character code.
TYPE AEKeyword = PACKED ARRAY[1..4] OF Char; {keyword for a }
{ descriptor record}
Constants are typically used for keywords. Here is a list of the keyword constants for Apple event attributes:
Attribute keyword Value Description
keyAddressAttr 'addr' Address of target or client application
keyEventClassAttr 'evcl' Event class of Apple event
keyEventIDAttr 'evid' Event ID of Apple event
keyEventSourceAttr 'esrc' Nature of the source application
keyInteractLevelAttr 'inte' Settings for allowing the Apple Event Manager to bring a server application to the foreground, if necessary, to interact with the user
keyMissedKeywordAttr 'miss' Keyword for first required parameter remaining in an Apple event
keyOptionalKeywordAttr 'optk' List of keywords for parameters of the Apple event that should be treated as optional by the target application
keyOriginalAddressAttr 'from' Address of original source of Apple event if the event has been forwarded (available only in version 1.01 or later versions of the Apple Event Manager)
keyReturnIDAttr 'rtid' Return ID for reply Apple event
keyTimeoutAttr 'timo' Length of time, in ticks, that the client will wait for a reply or a result from the server
keyTransactionIDAttr 'tran' Transaction ID identifying a series of Apple events
Here is a list of the keyword constants for commonly used Apple event parameters:
Parameter keyword Value Description
keyDirectObject '----' Direct parameter
keyErrorNumber 'errn' Error number parameter
keyErrorString 'errs' Error string parameter
The Apple Event Registry: Standard Suites defines additional keyword constants for Apple event parameters that can be used with specific Apple events.
The Apple Event Manager associates keywords with specific descriptor records by means of a keyword-specified descriptor record, a data structure of type AEKeyDesc that consists of a keyword and a descriptor record.
TYPE AEKeyDesc = {keyword-specified descriptor record}
RECORD
descKey: AEKeyword; {keyword}
descContent: AEDesc; {descriptor record}
END;
Figure 3-7 illustrates a keyword-specified descriptor record with the keyword keyEventClassAttr—the keyword that identifies an event class attribute. The figure shows the logical arrangement of the event class attribute for the Open Documents event shown in Figure 3-3 on page 3-10. The descriptor record in Figure 3-7 is identical to the one in Figure 3-6; its descriptor type is typeType, and the data to which its handle refers identifies the event class as kCoreEventClass.
Figure 3-7 A keyword-specified descriptor record for the event class attribute of an Open Documents event
Descriptor Lists
When extracting data from an Apple event, you use Apple Event Manager functions to copy data to a buffer specified by a pointer, or to return a descriptor record whose data handle refers to a copy of the data, or to return lists of descriptor records (called descriptor lists).
As previously noted, the descriptor record (of data type AEDesc) is the fundamental structure in Apple events, and it consists of a descriptor type and a handle to data. A descriptor list is a data structure of type AEDescList defined by the data type AEDesc—that is, a descriptor list is a descriptor record whose data handle refers to a list of other descriptor records (unless it is an empty list).
TYPE AEDescList = AEDesc; {list of descriptor records}
Like several other Apple Event Manager data structures, a descriptor list is identical to a descriptor record of data type AEDesc; the only difference is that the data in a descriptor list must always consist of a list of other descriptor records.
Figure 3-8 illustrates the logical arrangement of the descriptor list that specifies the direct parameter of the Open Documents event shown in Figure 3-3 on page 3-10. This descriptor list consists of a list of descriptor records that contain alias records to filenames. (See the chapter “Alias Manager” in Inside Macintosh: Files for a detailed description of alias records.)
Figure 3-8 A descriptor list for a list of aliases
The descriptor list in Figure 3-8 provides the data for a keyword-specified descriptor record. Keyword-specified descriptor records for Apple event parameters can in turn be combined in an AE record, which is a descriptor list of data type AERecord.
TYPE AERecord = AEDescList; {list of keyword-specified }
{ descriptor records}
The handle for a descriptor list of data type AERecord refers to a list of keyword-specified descriptor records that can be used to construct Apple event parameters. The Apple Event Manager provides routines that allow your application to create AE records and extract data from them when creating or responding to Apple events.
An AE record has the descriptor type typeAERecord and can be coerced to several other descriptor types. An Apple event record, which is different from an AE record, is another special descriptor list of data type AppleEvent and descriptor type typeAppleEvent.
TYPE AppleEvent = AERecord; {list of attributes and }
{ parameters necessary for }
{ an Apple event}
An Apple event record describes a full-fledged Apple event. Like the data for an AE record, the data for an Apple event record consists of a list of keyword-specified descriptor records. Unlike an AE record, the data for an Apple event record is divided into two parts, one for attributes and one for parameters. This division within the Apple event record allows the Apple Event Manager to distinguish between an Apple event’s attributes and its parameters.
Descriptor lists, AE records, and Apple event records are all descriptor records whose handles refer to a nested list of other descriptor records. The data associated with each data type may be organized differently and is used by the Apple Event Manager for different purposes. In each case, however, the data is identified by a handle in a descriptor record. This means that you can pass an Apple event record to any Apple Event Manager function that expects an AE record. Similarly, you can pass Apple event records and AE records, as well as descriptor lists and descriptor records, to any Apple Event Manager functions that expect records of data type AEDesc.
When you use the AECreateAppleEvent function, the Apple Event Manager creates an Apple event record containing the attributes for an Apple event’s event class, event ID, target address, return ID, and transaction ID. You then use Apple Event Manager functions such as AEPutParamDesc and AEPutAttributeDesc to add or modify attributes and to add any necessary parameters to the Apple event.
Figure 3-9 shows an example of a complete Apple event—a data structure of type AppleEvent containing a list of keyword-specified descriptor records that name the attributes and parameters of an Open Documents event. The figure includes the event class attribute shown in Figure 3-7 and the descriptor list shown in Figure 3-8, which forms the direct parameter—the keyword-specified descriptor record with the keyword keyDirectObject. The entire figure corresponds to the Open Documents event shown in Figure 3-3 on page 3-10.
The next two sections, “Responding to Apple Events” and “Creating and Sending Apple Events,” provide a quick overview of the steps your application must take to respond to and send Apple events.
Figure 3-9 Data structures within an Open Documents event
Responding to Apple Events
A client application typically uses the Apple Event Manager to create and send an Apple event requesting a service or information. A server application responds by using the Apple Event Manager to process the Apple event, extract data from the attributes and parameters of the Apple event, and if necessary add requested data to the reply event returned by the Apple Event Manager to the client application. The server usually provides its own Apple event handler for performing the action requested by the client’s Apple event.
As its first step in supporting Apple events, your application should support the required Apple events sent by the Finder. If you plan to implement publish and subscribe capabilities, your application must also respond to the Apple events sent by the Edition Manager. Your application should also be able to respond to the standard Apple events that other applications are likely to send to it or that it can send to itself. This section provides a quick overview of the tasks your application must perform in responding to Apple events.
To respond to Apple events, your application must
n set the appropriate flags in its 'SIZE' resource
n test for high-level events in its event loop
n provide Apple event handlers for the Apple events it supports
n use the AEInstallEventHandler function to install its Apple event handlers
n use the AEProcessAppleEvent function to process Apple events
Before your application can respond to Apple events sent from remote computers, the user of your application must allow network users to link to your application. To do this, the user selects your application in the Finder, chooses Sharing from the File menu, and then clicks the Allow Remote Program Linking checkbox. If the user has not yet started program linking, the Sharing command offers to display the Sharing Setup control panel so that the user can start program linking. The user must also authorize remote users for program linking by using the Users & Groups control panel. Program linking and setting up authenticated sessions are described in the chapter “Program-to-Program Communications Toolbox” in this book.
Accepting and Processing Apple Events
To accept or send Apple events (or any other high-level events), you must set the appropriate flags in your application’s 'SIZE' resource and include code to handle high-level events in your application’s main event loop.
Two flags in the 'SIZE' resource determine whether an application receives high-level events:
n The isHighLevelEventAware flag must be set for your application to receive any high-level events.
n The localAndRemoteHLEvents flag must be set for your application to receive high-level events sent from another computer on the network.
An Apple event (like all high-level events) is identified by a message class of kHighLevelEvent in the what field of the event record. You test the what field of the event record to determine whether it contains the value represented by the kHighLevelEvent constant; if your application defines any high-level events other than Apple events, you should also test the message field of the event record to determine whether the high-level event is something other than an Apple event. If the high-level event is not one that you’ve defined for your application, assume that it is an Apple event. (You are encouraged to use Apple events instead of defining your own high-level events whenever possible.)
After determining that an event is an Apple event, use the AEProcessAppleEvent function to let the Apple Event Manager identify the event. Figure 3-10 shows how the SurfWriter application accepts and begins to process an Apple event sent by the Finder.
Figure 3-10 Accepting and processing an Open Documents event
The AEProcessAppleEvent function first identifies the Apple event by examining the data in the event class and event ID attributes. The function then uses that data to call the Apple event handler that your application provides for that event. The Apple event handler extracts the pertinent data from the Apple event, performs the requested action, and returns a result. For example, if the event has an event class of kCoreEventClass and an event ID of kAEOpenDocuments, the AEProcessAppleEvent function calls your application’s handler for the Open Documents event.
Before your application attempts to accept or process any Apple events, it must use the AEInstallEventHandler function to install Apple event handlers. This function installs handlers in an Apple event dispatch table for your application; the Apple Event Manager uses this table to map Apple events to handlers in your application. When your application calls the AEProcessAppleEvent function to process an Apple event, the Apple Event Manager checks the Apple event dispatch table and, if your application has installed a handler for that Apple event, calls that handler. Figure 3-11 shows how the flow of control passes from your application to the Apple Event Manager and back to your application.
Figure 3-11 The Apple Event Manager calling the handler for an Open Documents event
About Apple Event Handlers
Your Apple event handlers must generally perform the following tasks:
n extract the parameters and attributes from the Apple event
n check that all the required parameters have been extracted
n locate any Apple event objects specified by object specifier records in the Apple event parameters
n if your application needs to interact with the user, use the AEInteractWithUser function to bring it to the foreground
n perform the action requested by the Apple event
n dispose of any copies of descriptor records that have been created
n add information to the reply Apple event if requested
This section describes how your application’s Apple event handlers can use the Apple Event Manager to accomplish some of these tasks. The chapter “Responding to Apple Events” in this book provides detailed information about handling Apple events and interacting with the user.
Extracting and Checking Data
You must use Apple Event Manager functions to extract the data from Apple events. You can also use Apple Event Manager functions to extract data from descriptor records, descriptor lists, and AE records. Most of these routines are available in two forms: they either return a copy of the data in a buffer or return a copy of the descriptor record for the data, including a copy of the data.
The following list shows the main functions you can use to access the data of an Apple event:
Function Description(continued)
AEGetParamPtr Uses a buffer to return a copy of the data contained in an Apple event parameter. Usually used to extract data of fixed length or known maximum length; for example, to extract the result code from the keyErrorNumber parameter of a reply Apple event.
AEGetParamDesc Returns a copy of the descriptor record or descriptor list for an Apple event parameter. Usually used to extract data of variable length; for example, to extract the descriptor list for a list of alias records specified in the direct parameter of the Open Documents event.
AEGetAttributePtr Uses a buffer to return a copy of the data contained in an Apple event attribute. Used to extract data of fixed length or known maximum length; for example, to determine the source of an Apple event by extracting the data from the keyEventSourceAttr attribute.
continued
AEGetAttributeDesc Returns a copy of the descriptor record for an attribute. Used to extract data of variable length; for example, to make a copy of a descriptor record containing the address of an application.
AECountItems Returns the number of descriptor records in a descriptor list. Used, for example, to determine the number of alias records for documents specified in the direct parameter of the
Open Documents event.
AEGetNthPtr Uses a buffer to return a copy of the data for a descriptor record contained in a descriptor list. Used to extract data of fixed length or known maximum length; for example, to extract the name and location of a document from the descriptor list specified in the direct parameter of the
Open Documents event.
AEGetNthDesc Returns a copy of a descriptor record from a descriptor list. Used to extract data of variable length; for example, to get the descriptor record containing an alias record from the list specified in the direct parameter of the Open Documents event.
You can specify the descriptor type of the resulting data for these functions; if this type is different from the descriptor type of the attribute or parameter, the Apple Event Manager attempts to coerce it to the specified type. In the direct parameter of the Open Documents event, for example, each descriptor record in the descriptor list is an alias record; each alias record specifies a document to be opened. As explained in the chapter “Introduction to File Management” of Inside Macintosh: Files, all your application usually needs is the file system specification (FSSpec) record of the document. When you extract the descriptor record from the descriptor list, you can request that the Apple Event Manager return the data to your application as a file system specification record instead of an alias record.
After extracting all known Apple event parameters, your handler should check that it retrieved all the parameters that the source application considered to be required. To do so, determine whether the keyMissedKeywordAttr attribute exists. If so, your handler has not retrieved all the required parameters, and it should return an error.
Although the Apple Event Registry: Standard Suites defines Apple event parameters as either required or optional, the Apple Event Manager does not enforce the definitions of required and optional events. Instead, the source application specifies, when it sends the event, which Apple event parameters the target can treat as if they were optional. For more information about optional parameters, see “Specifying Optional Parameters for an Apple Event,” which begins on page 5-7.
If any of the Apple event parameters include object specifier records, your handler should use the AEResolve function, other Apple Event Manager routines, and your own application-defined functions to locate the corresponding Apple event objects. For more information about locating Apple event objects, see “Working With Object Specifier Records,” which begins on page 3-32.
Interacting With the User
In some cases, the server may need to interact with the user when it handles an Apple event. For example, your handler for the Print Documents event may need to display a print options dialog box and get settings from the user before printing. By specifying flags to the AESetInteractionAllowed function, you can set preferences to allow user interaction with your application (a) only when your application is sending the Apple event to itself, (b) only when the client application is on the same computer as your application, or (c) for any event sent by any client application on any computer. In addition, your handler should always use the AEInteractWithUser function before displaying a dialog box or alert box or otherwise interacting with the user. The AEInteractWithUser function determines whether user interaction can occur and takes appropriate action depending on the circumstances.
Both the client and server specify their preferences for user interaction: the client specifies whether the server should be allowed to interact with the user, and the server specifies when it allows user interaction while processing an Apple event. The Apple Event Manager does not allow a server application to interact with the user in response to a client application’s Apple event unless at least two conditions are met: First, the client application must set flags in the sendMode parameter of the AESend function indicating that user interaction is allowed. Second, the server application must either set no user interaction preferences, in which case AEInteractWithUser assumes that only interaction with a client on the local computer is allowed; or it must set flags to the AESetInteractionAllowed function indicating that user interaction is allowed.
If these two conditions are met and if AEInteractWithUser determines that both the client and server applications allow user interaction under the current circumstances, AEInteractWithUser brings your application to the foreground if it isn’t already in the foreground. Your application can then display its dialog box or alert box or otherwise interact with the user. The AEInteractWithUser function brings your server application to the front either directly or after the user responds to a notification request.
For detailed information about how to specify flags to the AESetInteractionAllowed function and how the Apple Event Manager determines whether user interaction is allowed, see the section
“Interacting With the User,” which begins on page 4-45.
Performing the Requested Action and Returning a Result
When your application responds to an Apple event, it should perform the standard action requested by that event. For example, your application should respond to the Open Documents event by opening the specified documents in titled windows just as if the user had selected each document from the Finder and then chosen Open from the File menu.
Many Apple events can ask your application to return data. For instance, if your application is a spelling checker, the client application might expect your application to return data in the form of a list of misspelled words. Figure 3-14 on page 3-38 shows a similar example: a Get Data event that asks the server application to locate a specific Apple event object and return the data associated with it.
If the client application requests a reply, the Apple Event Manager prepares a reply Apple event by passing a default reply Apple event to your handler. If the client application does not request a reply, the Apple Event Manager passes a null descriptor record—that is, a descriptor record of type typeNull whose data handle has the value NIL—to your handler instead of a default reply Apple event. The default reply Apple event has no parameters when it is passed to your handler, but your handler can add parameters to it. If your application is a spelling checker, for example, you can return a list of misspelled words in a parameter. However, your handler should check whether the reply Apple event exists before attempting to add any attributes or parameters to it. Any attempt to add an Apple event attribute or parameter to a null descriptor record generates an error.
When you extract a descriptor record using the AEGetParamDesc, AEGetAttributeDesc, AEGetNthDesc, or AEGetKeyDesc function, the Apple Event Manager creates a copy of the descriptor record for you to use. When your handler is finished using a copy of a descriptor record, you should dispose of it—and thereby deallocate the memory used by its data—by calling the AEDisposeDesc function.
Note
Outputs from functions such as AEGetKeyPtr and other routines whose names end in -Ptr use a buffer rather than a descriptor record to return data. Because these functions don’t require the use of AEDisposeDesc, it is preferable to use them for any data that is not identified by a handle.u
Your Apple event handler should always set its function result either to noErr if it successfully handles the Apple event or to a nonzero result code if an error occurs. If your handler returns a nonzero result code, the Apple Event Manager adds a keyErrorNumber parameter to the reply Apple event (unless you have already added a keyErrorNumber parameter). This parameter contains the result code that your handler returns. The client should check whether the keyErrorNumber parameter exists to determine whether your handler performed the requested action. In addition to returning a result code, your handler can also return an error string in the keyErrorString parameter of the reply Apple event. The client can use this string in an error message to the user.
If the client application requested a reply, the Apple Event Manager returns the reply Apple event, which is identified by the event class kCoreEventClass and by the event ID kAEAnswer. When the client has finished using the reply Apple event, it should dispose of both the reply event and the original event—and thereby deallocate the memory they use—by calling the AEDisposeDesc function. The Apple Event Manager takes care of disposing both the Apple event and the reply Apple event after a server application’s handler returns to AEProcessAppleEvent, but a server application is responsible for disposing of any Apple event data structures it creates while extracting data from the Apple event.
Figure 3-12 shows the entire process of responding to an Apple event.
Figure 3-12 Responding to an Open Documents event
When your handler returns a result code to the Apple Event Manager, you have finished your response to the client application’s Apple event.
Creating and Sending Apple Events
Your application can use Apple events to request services or information from other applications, send information to other applications, or trigger actions within your application. For example, you can use the core Apple event Get Data to request specific data from another application’s documents. Similarly, you can use other Apple events to request services—for example, asking a spell-checking application to check the text in a document created by your application. Consult the Apple Event Registry: Standard Suites for the format and function of the standard Apple events that you want your application to send.
To communicate with another application by sending an Apple event, your application must
n set the appropriate flags in its 'SIZE' resource
n create an Apple event record by calling the AECreateAppleEvent function
n use Apple Event Manager functions to add parameters and any additional attributes to the Apple event
n call the AESend function to send the Apple event
n dispose of any copies of descriptor records that you have created
n handle the reply Apple event (if necessary)
The sections that follow describe how your application can use the Apple Event Manager to accomplish these tasks. The chapter “Creating and Sending Apple Events” in this book provides detailed information about creating and sending Apple events.
To act as a server for your application, the target application must support high-level events and must be running. The server can be your own application, another application running on the user’s computer, or an application running on another user’s computer connected to the network.
Your application should also allow the user to choose among the various applications available as servers. The PPCBrowser function allows users to select target applications on their own computers or on computers connected to the network. The PPCBrowser function presents a standard user interface for choosing a target application, much as the Standard File Package provides a standard user interface for opening and saving files. See the chapter “Program-to-Program Communications Toolbox” in this book for details on using the PPCBrowser function.
If the server application is on a remote computer on a network, the user of that computer must allow program linking to the server application. The user of the server application does this by selecting the application icon in the Finder, choosing Sharing from the File menu, then clicking the Allow Remote Program Linking checkbox. If the user has not yet started program linking, the Sharing command offers to display the Sharing Setup control panel so that the user can start program linking. The user must also authorize remote users for program linking by using the Users & Groups control panel. Program linking and setting up authenticated sessions are described in the chapter “Program-to-Program Communications Toolbox” in this book.
Creating an Apple Event Record
Use the AECreateAppleEvent function to create an Apple event record. Using the arguments you pass to the AECreateAppleEvent function, the Apple Event Manager constructs the data structures describing the event class, the event ID, and the target address attributes of an Apple event. The event class and event ID, of course, identify the particular event you wish to send. The target address identifies the intended recipient of the Apple event.
You can specify two other attributes with the AECreateAppleEvent function: the reply ID and the transaction ID. For the reply ID attribute, you usually specify the kAutoGenerateReturnID constant to the AECreateAppleEvent function. This constant ensures that the Apple Event Manager generates a unique return ID for the reply Apple event returned from the server. For the transaction ID attribute, you usually specify the kAnyTransactionID constant, which indicates that this Apple event is not one of a series of interdependent Apple events.
Adding Apple Event Attributes and Parameters
The Apple event record created with the AECreateAppleEvent function serves as a foundation for the Apple event you want to send. Descriptor records and descriptor lists are the building blocks from which the complete Apple event record is constructed. To create descriptor records and descriptor lists and add items to a descriptor list, use the following functions:
Function Description
AECreateDesc Takes a descriptor type and a pointer to data and converts them into a descriptor record
AECreateList Creates an empty descriptor list or AE record.
AEPutPtr Takes a descriptor type and a pointer to data and adds the data to a descriptor list as a descriptor record; used, for example, to add to a descriptor list a number used as the parameter of an Apple event requesting a calculation.
AEPutDesc Adds a descriptor record to a descriptor list; used, for example, to add to a descriptor list an alias record used as the direct parameter of an Apple event requesting file manipulation.
To add the remaining attributes and parameters necessary for your Apple event to the Apple event record, you can use these additional Apple Event Manager functions:
Function Description
AEPutParamPtr Takes a keyword, descriptor type, and pointer to data and adds the data to an Apple event record as a parameter with the specified keyword (replacing any existing parameter with the same keyword); used, for example, to put numbers into the parameters of an Apple event that asks the server to perform a calculation.
AEPutParamDesc Takes a keyword and a descriptor record and adds the descriptor record to an Apple event record as a parameter with the specified keyword (replacing any existing parameter with the same keyword); used, for example, to place a descriptor list containing alias records into the direct parameter of an Apple event that requests a server to manipulate files.
AEPutAttributePtr Takes a keyword, descriptor type, and pointer to data and adds the descriptor record to an Apple event record as an attribute with the specified keyword (replacing any existing attribute with the same keyword); used, for example, to change the transaction ID of an Apple event record that is waiting to be sent.
AEPutAttributeDesc Takes a keyword and a descriptor record and adds the descriptor record to an Apple event record as an attribute with the specified keyword (replacing any existing attribute with the same keyword); used, for example, to replace the descriptor record used for the target address attribute in an Apple event record waiting to be sent.
Apple event parameters for core events and functional-area events can include descriptions of Apple event objects in special descriptor records called object specifier records. For an overview of object specifier records, see “Working With Object Specifier Records,” which begins on page 3-32.
Sending an Apple Event and Handling the Reply
After you add all the attributes and parameters required for the Apple event, use the AESend function to send the Apple event. The Apple Event Manager uses the Event Manager to transmit the Apple event to the server application.
The AESend function requires that you specify whether your application should wait for a reply from the server. If you specify that you want a reply, the Apple Event Manager prepares a reply Apple event for your application by passing a default reply Apple event to the server. The Apple Event Manager returns any nonzero result code from the server’s handler in the keyErrorNumber parameter of the reply Apple event. The server can return an error string in the keyErrorString parameter of the reply Apple event. The server can also use the reply Apple event to return any data you requested—for example, the results of a numeric calculation or a list of misspelled words.
You specify how your application should wait for a reply by using one of these flags in the sendMode parameter of the AESend function:
Flag Description
kAENoReply Your application does not want a reply Apple event.
kAEQueueReply Your application wants a reply Apple event; the reply appears in your event queue as soon as the server has the opportunity to process and respond to your Apple event.
kAEWaitReply Your application wants a reply Apple event and is willing to give up the processor while waiting for the reply; for example, if the server application is on the same computer as your application, your application yields the processor to allow the server to respond to your Apple event.
If you specify the kAEWaitReply flag, you should provide an idle function. This function should process any non-high-level events that occur while your application is waiting for a reply. You supply a pointer to your idle function as a parameter to the AESend function. So that your application can process other Apple events while it is waiting for a reply, you can also specify an optional filter function to the AESend function.
If you specify the kAENoReply flag, the reply Apple event prepared by the Apple Event Manager for the server application consists of a null descriptor record.
If your Apple event may require the user to interact with the server application (for example, to specify print or file options), you can communicate your user interaction preferences to the server by specifying additional flags in the sendMode parameter of the AESend function. These flags specify the conditions, if any, under which the server application can interact with the user and, if interaction is allowed, whether the server should come directly to the foreground or post a notification request.
The server application specifies its own preferences for user interaction by specifying flags to the AESetInteractionAllowed function, as described in the previous section. The interaction of the client and server applications’ preferences is explained in detail in “Interacting With the User,” which begins on page 4-45.
After you send an Apple event, your application is responsible for disposing of the Apple event record—and thereby deallocating the memory its data uses—by calling the AEDisposeDesc function. If you create one descriptor record and add it to another, the Apple Event Manager adds a copy of the newly created one to the existing one and also makes a copy of the associated data. For example, you might use the AECreateDesc function to create a descriptor record that you wish to add to an Apple event. When you use the AEPutParamDesc function, it adds a copy of your newly created descriptor record, including its data, as a parameter to an existing Apple event. When you no longer need the original descriptor record, you should call AEDisposeDesc to dispose of it.
Your application should dispose of all the descriptor records that are created for the purposes of adding parameters and attributes to an Apple event. You normally dispose of your Apple event and its reply after you receive a result from the AESend function. You should dispose of these even if AESend returns an error result.
If you specify the kAEWaitReply flag, the reply Apple event is returned in a parameter you pass to the AESend function. If you specify the kAEQueueReply flag to the AESend function, the reply Apple event is returned in the event queue. In this case, the reply is identified by the event class kCoreEventClass and the event ID kAEAnswer. Your application processes reply events in its event queue in the same way that server applications process Apple events.
Your application should check for the existence of the keyErrorNumber parameter of the reply Apple event to ensure that the server performed the requested action. The server can also return, in the keyErrorString parameter, any error messages you need to display to the user.
Whenever a server application provides an error string, it should also provide an error number. However, you can’t count on all server applications to do so. The absence of the keyErrorNumber parameter doesn’t necessarily mean that there won’t an error string provided in the keyErrorString parameter. A client application should therefore check for both the keyErrorNumber and keyErrorString parameters before assuming that no error has occurred. If a string has been provided without an error number, an error has occurred.
After extracting the information it needs from the reply event, your handler should dispose of the reply by calling the AEDisposeDesc function. Similarly, when your handler no longer needs descriptor records it has extracted from the reply, it should call AEDisposeDesc to dispose of them.
The next section provides an overview of the way a source application identifies Apple event objects supported by a target application. If you are starting by supporting only the Required suite and the Apple events sent by the Edition Manager, you can skip the next section and go directly to “About the Apple Event Manager,” which begins on page 3-48.
Working With Object Specifier Records
Most of the standard Apple events allow the source application to refer, in an Apple event parameter, to Apple event objects within the target application or its documents. The Apple Event Manager allows applications to construct and interpret such references by means of a standard classification system for Apple event objects. This system, described in detail in the Apple Event Registry: Standard Suites, is summarized in “The Classification of Apple Event Objects,” which begins on page 3-39. A description in an Apple event parameter that uses this classification system takes the form of an object specifier record.
An object specifier record is a descriptor record of descriptor type typeObjectSpecifier that describes the location of one or more Apple event objects: for example, the table “Summary of Sales” in the document “Sales Report,” or the third row in that table, or the last row of the column “Totals.” With the aid of application-defined functions, the Apple Event Manager can conduct a step-by-step search according to such instructions in an object specifier record, locating first the document, then the table, then other objects, and so on until the requested object has been identified. Object specifier records can specify many combinations of identifying characteristics that cannot be specified using one of the simple data types.
This section introduces object specifier records and the organization of their data. You need to read this section (a) if you plan to support the Core suite or any of the standard functional-area suites and (b) if you want to make your application scriptable—that is, capable of responding to scripts written in a scripting language.
IMPORTANT
An object specifier record identifies one or more Apple event objects among many; it contains a description of each object, not the object itself. An Apple event object described by an object specifier record exists only in the server application’s document or in the server application itself.s
A client application cannot retrieve an Apple event object from a server application unless the server application can accurately locate it. Thus, to locate characters of a specific color, a server application must be able to identify a single character’s color; to locate a character in a cell, a server application must be able to locate both the table and the cell.
A client application can create object specifier records for use as Apple event parameters. Scripting components can also create object specifier records as Apple event parameters for the Apple events they generate in the course of executing a script. A server application that receives an Apple event containing an object specifier record should resolve the object specifier record—that is, locate the requested Apple event objects.
To respond to core and functional-area Apple events received by your application, you must first define a hierarchy of Apple event objects for your application that you want other applications or scripting languages to be able to describe. The Apple event objects for your application should be based as closely as possible on the standard object classes described by the Apple Event Registry: Standard Suites. After you have decided which of the standard Apple event objects make sense for your application, you can write functions that locate objects on the basis of information in an object specifier record. If you want your application to send specific Apple events to other applications, you must also write functions that can create object specifier records and add them to Apple events. Your application does not need to create object specifier records in order to be scriptable. However, to write functions that can help the Apple Event Manager resolve object specifier records, you need to know how they are constructed.
“Finding Apple Event Objects,” which begins on page 3-46, provides an overview of the way the Apple Event Manager works with your application-defined functions to locate the Apple event objects described in an object specifier record. The chapter “Resolving and Creating Object Specifier Records” in this book describes in detail how to support object specifier records as a server or client application.
Data Structures Within an Object Specifier Record
The organization of the data for an object specifier record is nearly identical to that of the data for an AE record. An object specifier record is a structure of data type AEDesc whose data handle usually refers to four keyword-specified descriptor records describing one or more Apple event objects. An AE record is a structure of data type AERecord whose data handle refers to one or more Apple event parameters.
The four keyword-specified descriptor records for an object specifier record provide information about the requested Apple event object or objects.
Keyword Description of data
keyAEDesiredClass Four-character code indicating the object class ID
keyAEContainer A description of the container for the requested object, usually in the form of another object specifier record
keyAEKeyForm Four-character code for the key form, which indicates how to interpret the key data
keyAEKeyData Key data, used to distinguish the desired Apple event object from other objects of the same object class in the same container
For example, the data for an object specifier record identifying a table named “Summary of Sales” in a document named “Sales Report” consists of four keyword-specified descriptor records that provide the following information:
n the object class ID for a table
n another object specifier record identifying the document “Sales Report” as the container for the table
n a key form constant indicating that the key data contains a name
n key data that consists of the string “Summary of Sales”
The object class ID specifies the Apple event object class to which the object belongs. An Apple event object class is a category for Apple event objects that share specific characteristics (see “Apple Events and Apple Event Objects” on page 3-6). The characteristics of each object class are listed in the Apple Event Registry: Standard Suites. For example, the Core suite defines object classes for documents, paragraphs, words, windows, and floating windows. The first keyword-specified descriptor record in an object specifier record uses a four-character code or a constant to specify the object class ID. The object class for words, for example, can be identified by either the object class ID 'cwor' or the constant cWord.
Note
The object class ID identifies the object class of an Apple event object described in an object specifier record, whereas the event class and event ID identify an Apple event.u
The container for an Apple event object is usually another Apple event object. For example, the container for a document might be a window, and the container for characters, delimited items, or a word might be another word, a paragraph, or a document. The container is identified by the second keyword-specified descriptor record in an object specifier record; usually this is another object specifier record. The container can also be specified by a null descriptor record, which indicates a default container or a container already known to the Apple Event Manager.
The descriptor record in an object specifier record that identifies an Apple event object’s container can in turn use another object specifier record to identify the container’s container, and so on until the Apple event object is fully specified. For example, an object specifier record identifying a paragraph might specify the paragraph’s container with another object specifier record that identifies a page. That object specifier record might in turn specify the page’s container with another object specifier record identifying a document. The ability to nest one object specifier record within another in this way makes it possible to identify elements such as “the first row in the table named ‘Summary of Sales’ in the document named ‘Sales Report.’”
The key form and key data distinguish the desired Apple event object from other Apple event objects of the same object class. The key form describes the form the key data takes. The third keyword-specified descriptor record in an object specifier record usually specifies the key form with one of seven standard constants:
Key form Value Corresponding key data
formPropertyID 'prop' Property ID for an element’s property
formName 'name' Element’s name
formUniqueID 'ID ' A value that uniquely identifies an object within its container or across an application
formAbsolutePosition 'indx' An integer or other constant indicating the position of one or more elements in relation to the beginning or end of their container
formRelativePosition 'rele' A constant that specifies the element just before or after the container
formTest 'test' Descriptor records that specify a test
formRange 'rang' Descriptor records that specify a group of elements between two other elements
A key form of formPropertyID indicates key data that specifies a property. A property of an Apple event object is a specific characteristic of that object that can be identified by a constant. The properties associated with the object class for documents include the name of the document and a flag indicating whether the document has been modified since the last save. The properties associated with the object class for words include color, font, point size, and style.
Figure 3-13 shows the structure of a typical object specifier record: four keyword-specified descriptor records that specify the class ID, the container, the key form, and the key data. These four keyword-specified descriptor records are the data for a descriptor record (AEDesc) of descriptor type typeObjectSpecifier. Note the similarities between the object specifier record shown in Figure 3-13 and the Apple event record shown in Figure 3-9 on page 3-19. Like an Apple event record or an AE record, an object specifier record consists of a list of keyword-specified descriptor records.
Figure 3-13 shows the structure of a simple object specifier record that specifies the key form formPropertyID, formName, or formAbsolutePosition. For detailed information about the structure of object specifier records that specify the other key forms, see the chapter “Resolving and Creating Object Specifier Records” in this book.
Figure 3-13 Data structures within a simple object specifier record
Figure 3-14 shows the object specifier record for the Get Data event previously illustrated in Figure 3-4 on page 3-11. The object class ID tells the SurfWriter application that the requested data is an element of class cTable. The container for the table is the document “Sales Report.” The key form is formName, which tells the server application that the key data identifies the Apple event object by name. The key data is the name of the table.
Figure 3-14 An object specifier record in a Get Data event
To add an object specifier record to an Apple event as one of its parameters, your application must first create the object specifier record. “Creating Object Specifier Records,” which begins on page 6-55, describes the Apple Event Manager routines for creating object specifier records.
To respond to Apple events that include object specifier records, your application should use the standard classification system for Apple event objects and provide functions that can locate those objects within your application or its documents. The next section summarizes the classification of Apple event objects as defined in the Apple Event Registry: Standard Suites.
The Classification of Apple Event Objects
To create or resolve object specifier records, your application should use the classification of Apple event objects defined by the Apple Event Registry: Standard Suites. This section summarizes the concepts that underlie that classification system. You should have a copy of the Apple Event Registry: Standard Suites available for reference purposes while you read this section.
You do not need to write your application in an object-oriented programming language in order to support Apple event objects in your application. However, you must understand the classification system described in this section in order to classify Apple event objects in your application and to write routines that can locate them on the basis of information contained in object specifier records.
Object Classes
Except for the concept of inheritance, Apple event objects are different from the objects used in object-oriented programming languages. Apple event objects are distinct items in a server application or any of its documents that can be specified by an object specifier record in an Apple event sent by a client application. Apple event objects are often, but not always, items that a user can differentiate and manipulate within an application, such as words, paragraphs, shapes, windows, or style formats. Every Apple event object can be classified according to its object class, which defines both its characteristics and its behavior. The object classes listed in the Apple Event Registry: Standard Suites provide a method of describing Apple event objects that all applications can understand. Object classes permit more flexibility than simple descriptor types; for example, a word can be defined as a simple string, or it can be defined as an Apple event object with specific characteristics such as font or style.
Note
The definition of an object class only specifies conventions that determine how applications should handle Apple event objects that belong to that class. Your application must make sure that it uses the conventions correctly; they are not enforced by the Apple Event Manager.u
Each object class is identified by a four-character object class ID, which can also be represented by a constant. Constants for object classes always begin with the letter c.
The definition of an object class specifies its superclass, which is the object class from which a subclass (the class being defined) inherits some of its characteristics. Characteristics can also be inherited from special object classes, called abstract superclasses, that are used only in definitions of object classes and do not refer to real Apple event objects. The pattern of inheritance among object classes is called the object class inheritance hierarchy. Figure 3-15 shows a portion of this hierarchy. The abstract superclass cObject is at the top of the hierarchy and is therefore the only object class that has no superclass. At the next level are cText, which is a regular object class, and cOpenableObject, which is an abstract superclass. Both are subclasses of cObject and superclasses for their own subclasses. The object classes cWord, cItem, and cChar are all subclasses of cText. Similarly, cWindow, cDocument, and cFile are subclasses of cOpenableObject. Every object class inherits all the characteristics of its superclass and can also add characteristics of its own.
Figure 3-15 Superclasses and subclasses
Here are some of the object classes defined for the Core suite:
Class Class ID Description
cChar 'cha ' Text characters
cDocument 'docu' Macintosh documents
cFile 'cfil' Macintosh files
cSelection 'csel' User or application selections
cText 'ctxt' Series of characters
cWindow 'cwin' Standard Macintosh windows
Here are some of the object classes defined for the Text suite:
Class Class ID Description
cChar 'cha ' Text characters
cLine 'clin' Lines of text
cParagraph 'cpar' Paragraphs
cText 'ctxt' Series of characters
cTextFlow 'cflo' Text flows
cWord 'cwor' Words
As you can see, some object classes, such as cChar and cText, are defined in more than one suite. For example, the definition of the cText object class in the Text suite is an extension of the cText object class defined in the Core suite; it duplicates all the characteristics of the Core suite object class and adds some of its own. Like a word in a dictionary, one object class ID can have several related definitions. You can choose to support the definition that best suits your application; or, if necessary, you can create extensions of your own. The extension of an object class is different from inheritance between object classes. An extension of a standard object class provides additional ways of describing an Apple event object of that class, whereas the object class inheritance hierarchy determines the pattern of characteristics shared by different object classes.
The definition of an object class always specifies a default descriptor type. Suppose, for example, that a client application sends a Get Data, Cut, or Copy event that specifies an Apple event object but does not specify a descriptor type for the returned data. In this case, the server application returns a descriptor record of the default descriptor type for the object class of the specified Apple event object. For example, the default descriptor type for Apple event objects of class cWord is typeIntlText, a descriptor type that specifies an undelimited string of characters in a specific language and script system. The client application can also request that the data be returned in a descriptor record of some other data type.
The definition of an object class includes three lists of characteristics: properties, element classes, and Apple events that support the object class. (The next section describes properties and element classes.) Any or all of these characteristics may be inherited from a superclass. An Apple event is listed for an object class if its parameters can specify objects of that class. The definition for cWindow, for example, lists 12 Apple events, including the Open, Close, and Move events, whose parameters can include object specifier records that specify windows. The cWindow class inherits all of these Apple events from its abstract superclass, cOpenableObject.
The Apple Event Registry: Standard Suites also defines primitive object classes, which describe Apple event objects that contain a single value. For example, the cBoolean, cLongInteger, and cAlias object classes are all primitive object classes. The object class ID for a primitive object class is the same as the four-character value of its descriptor type. Primitive object classes contain no properties; they contain only the value of the data.
Properties and Elements
The properties listed for an object class can be used to identify characteristics of Apple event objects that belong to that class. Each property is identified by a four-character property ID, which can also be represented by a constant. Constants for properties always begin with the letter p.
Here are constants and property IDs for some properties:
Property Property ID Description
pName 'pnam' Name of an Apple event object
pBounds 'pbnd' Coordinates of a window
pVisible 'pvis' Indicates whether a window is visible
pIsModal 'pmod' Indicates whether a window is modal
pClass 'pcls' Class ID of an Apple event object
pFont 'font' Font
pTextStyle 'txst' Text style
pColor 'colr' Text color
pTextPointSize 'ptps' Point size
pScriptTag 'psct' Script system identifier
pFillColor 'flcl' Fill color
The property of an Apple event object is itself defined as a single Apple event object whose container is the object to which the property belongs. For example, the pFont property of a word is defined by the name of a font, such as New York; the string that identifies the font is an Apple event object of class cText.
The constant cProperty specifies the object class for any object specifier record that identifies a property.
CONST cProperty = 'prop';
An object specifier record for a property specifies cProperty as the object class ID, the Apple event object to which the property belongs as the container, formPropertyID as the key form, and a constant such as pFont as the key data.
The elements of a specific Apple event object are the other Apple event objects it contains, excluding those that define its properties. An object specifier record for an element specifies the Apple event object in which the element is located as the container and can specify any key form except formPropertyID. Each object class definition in the Apple Event Registry: Standard Suites includes a list of element classes, which are the object classes of the elements that an Apple event object can contain.
An Apple event object contains exactly one of each of its properties, whereas it can contain no elements or many elements of the same element class. In general, a property of an object describes something about that object; a property can be examined or changed but never deleted. An element can be one or more discrete objects contained in another object and can usually be deleted.
For example, because a paragraph can contain one or more words, one of the element classes listed for the object class cParagraph is the object class cWord. Individual words can be deleted from a paragraph. However, even though a word in a paragraph can be in a different font from the words around it, a paragraph can have only one pFont property. This property is defined as the font of the first character in the paragraph and consists of the name of a font. The paragraph’s pFont property can be changed but not removed.
The properties and element classes listed for each object class definition in the Apple Event Registry: Standard Suites can be inherited from a superclass, or they can originate with a subclass. Figure 3-16 illustrates the object class inheritance hierarchy for the object class cWindow in the Core suite. Boldface terms in the figure represent those properties, element classes, or Apple events that are not inherited. The object class cWindow includes all the properties and Apple events of its superclass, cOpenableObject, which in turn includes all the properties and Apple events of its superclass, cObject. The object class cWindow also includes 11 properties and one element class that originate with cWindow and are not inherited.
The pClass property—the property that specifies the four-character class ID—originates with cObject. Because the definitions of all object classes are ultimately derived from cObject, pClass is inherited by all object classes. The definition for cObject also lists ten Apple events, which include common events such as Get Data, Move, and Delete Element. Because cObject is at the top of the object class inheritance hierarchy, these ten Apple events can use object specifier records that describe Apple event objects of any object class as a direct parameter. Like all abstract superclasses, cObject does not correspond to a real Apple event object, so its definition does not list any element classes. Unlike any other object class, cObject is at the top of the object class inheritance hierarchy and therefore does not have a superclass.
Figure 3-16 The object class inheritance hierarchy for the object class cWindow
The chain of containers that determine the location of one or more Apple event objects is called the container hierarchy. The container hierarchy, which specifies the location of real Apple event objects, is different from the object class inheritance hierarchy, which is an abstract concept that determines which properties, element classes, and Apple events an object class inherits from its superclass. For example, the container hierarchy for an Apple event object of class cWord can vary from one word to another, because various combinations of other Apple event objects, such as a document, a paragraph, a delimited string, or another word, can contain a word.
Applications that support Apple event objects must be able to identify the order of several elements of the same class that are contained within another Apple event object. For example, each word in a paragraph should have an identifiable order, such as the 5th word or the 12th word. This allows other applications to identify Apple event objects by describing their absolute position within a container.
Figure 3-17 shows an Apple event object of object class cWord—the word “Sales”—contained in another Apple event object of object class cParagraph. (Both these object classes are defined in the Text suite.) The figure shows only a portion of the container hierarchy for the word, since a complete description of the word would also include the containers that specify the location of the paragraph.
Your application must take account of the definitions in the Apple Event Registry: Standard Suites for any object classes you want to support. For example, the definition for the object class cText lists paragraphs, lines, words, and characters as Apple event objects that can be contained in Apple event objects of class cText. To support Apple events that refer to elements of object class cText, your application should associate the cText object class with paragraphs, lines, words, and characters in its documents. The list of properties defined for class cText includes the properties pColor, pFont, pPointSize, pScriptTag, and pTextStyles. If you want to support Apple events that distinguish a boldface 12-point word of object class cText from an italic 14-point word, for example, your application must associate the point size and style of text in its documents with the properties pPointSize and pTextStyles defined for class cText.
Figure 3-17 An Apple event object of class cWord contained in an Apple event object of class cParagraph
Finding Apple Event Objects
Most of the Apple events in the Core suite and the functional-area suites defined in the Apple Event Registry: Standard Suites can include parameters that consist of object specifier records. Your application’s handlers for these events can use the AEResolve function to resolve object specifier records: that is, to locate the Apple event objects they describe.
The AEResolve function parses an object specifier record and performs related tasks that are the same for all object specifier records. When necessary, the AEResolve function calls application-defined functions to perform tasks that are unique to the application, such as locating a specific Apple event object in the application’s data structures.
Your application can provide two kinds of application-defined functions for use by AEResolve. Object accessor functions locate Apple event objects. Every application that supports simple object specifier records must provide one or more object accessor functions. Object callback functions perform other tasks that only an application can perform, such as counting, comparing, or marking Apple event objects.
Each time AEResolve calls one of your application’s object accessor functions successfully, the object accessor function returns a special descriptor record, called a token, that identifies either an element in a specified container or a property of a specified Apple event object. The token can be of any descriptor type, including descriptor types you define yourself.
You install object accessor functions by using the AEInstallObjectAccessor function. Much like the AEInstallEventHandler function, AEInstallObjectAccessor uses an object accessor dispatch table to map requests for Apple event objects to the appropriate object accessor functions in your application. These requests refer to objects of a specified object class in containers identified by a token of a specified descriptor type.
Responding to an Apple event that includes an object specifier record typically involves these steps:
1. After determining that the event is an Apple event, your application calls AEProcessAppleEvent.
2. The AEProcessAppleEvent function uses the Apple event dispatch table to dispatch the event to the your application’s handler for that event.
3. The Apple event handler extracts the Apple event parameters, and passes the object specifier records they contain to AEResolve.
4. The AEResolve function uses the object accessor dispatch table to call one or more object accessor functions, one at a time, that can identify the nested Apple event objects described by each object specifier record. Each object accessor function returns a token for the object it finds, which in turn helps to determine which object accessor function the AEResolve function will use to locate the next Apple event object.
5. The AEResolve function returns the final token for the requested object to the application’s handler.
The resolution of an object specifier record always begins with the outermost container it specifies. For example, to locate a table named “Summary of Sales” in the document named “Sales Report,” the AEResolve function first calls an object accessor function that can locate the document, then uses the token returned by that function to identify an object accessor function that can locate the table. It then returns the token for the table to the Apple event handler that called AEResolve.
The chapter “Resolving and Creating Object Specifier Records” in this book describes in detail how to resolve object specifier records and how to write and install object accessor and object callback functions.
About the Apple Event Manager
You can use the Apple Event Manager to
n respond to Apple events as a server application
n create and send Apple events as a client application
n resolve and create object specifier records
n support Apple event recording
This section briefly summarizes the steps involved in providing each kind of support and tells where to find the relevant information in this book.
Supporting Apple Events as a Server Application
You do not need to implement all Apple events at once. You can begin by supporting just the required events and, if necessary, the events sent by the Edition Manager. The beginning of the section “Handling Apple Events” on page 4-4 describes how to provide this minimal level of support.
It is relatively easy to respond to the required events and the events sent by the Edition Manager. If, however, your application cannot respond to any other Apple events, other applications will not be able to request services that involve locating specific Apple event objects within your application or its documents, and users will not be able to control your application by executing scripts. To respond to Apple events it is likely to receive from other applications or from scripting components, your application must be able to respond to the appropriate core and functional-area Apple events.
Once you have provided the basic level of support for the Required suite and for events sent by the Edition Manager, you should
n decide which other Apple event suites you want to support
n define the hierarchy of Apple event objects within your application that you want scripting components or other applications to be able to identify—that is, which Apple event objects can be contained by other Apple event objects in your application
n write handlers for the Apple events you support, and install corresponding entries in your application’s Apple event dispatch table
To decide which Apple event suites you want to support and how to define the hierarchy of Apple event objects in your application, consult the Apple Event Registry: Standard Suites and evaluate which Apple events and Apple event object classes make sense for your application. If necessary, you can extend the definitions of the standard Apple events and Apple events objects to cover special requirements of your application. It is better to extend the standard definitions rather than to define your own custom Apple events, because only those applications that choose to support your custom Apple events explicitly will be able to make use of them.
The chapter “Responding to Apple Events” in this book describes how to write Apple event handlers and related routines. The chapter “Resolving and Creating Object Specifier Records” describes how to resolve object specifiers in an Apple event that describes Apple event objects in your application or its documents.
If your application can respond to Apple events, you can make it scriptable simply by adding an 'aete' resource. Scripting components use your application’s 'aete' resource to obtain information about the Apple events and corresponding human-language terminology that your application supports. The chapter “Apple Event Terminology Resources” in this book describes how to optimize your implementation of Apple events for use by scripting components and how to create an 'aete' resource.
Supporting Apple Events as a Client Application
Because users can send Apple events to a variety of applications simply by executing a script, many applications have no need to send Apple events. However, if you want to factor your application for recording, or if you want your application to send Apple events directly to other applications, you can use Apple Event Manager routines to create and send Apple events.
To send an Apple event, you must
n create the Apple event
n add parameters and attributes
n use the AESend function to send the event
The chapter “Creating and Sending Apple Events” in this book describes how to perform these tasks.
Supporting Apple Event Objects
If your application responds to core and functional-area Apple events, it must also be able to resolve object specifier records that describe the objects on which those Apple events can act. In addition to the tasks described in the chapter “Responding to Apple Events,” you must perform the following tasks to handle Apple events that contain object specifier records:
n Write object accessor functions that can locate the Apple event objects you support, and install corresponding entries in your application’s object accessor dispatch table.
n Write any object callback functions that you decide to provide. To handle object specifier records that specify a test, your application must provide at least two object callback functions: one that counts objects and one that compares them.
n Call AEResolve from your Apple event handlers whenever an Apple event parameter includes an object specifier record.
The chapter “Resolving and Creating Object Specifier Records” describes how to perform these tasks. It also describes how applications that send Apple events to themselves or directly to other applications can create object specifier records.
Supporting Apple Event Recording
If you make your application scriptable, you may also want to make it recordable. Users of recordable applications can record their actions in the form of Apple events that a scripting component translates into a script. When a user executes a recorded script, the scripting component sends the same Apple events to the application in which they were recorded.
To make your application recordable, you should use Apple events to report user actions to the Apple Event Manager in terms of Apple events. One way to do this is to separate the code that implements your application’s user interface from the code that actually performs work when the user manipulates the interface. This is called factoring your application. A factored application acts as both the client and server application for Apple events it sends to itself in response to user actions. When recording is turned on, the Apple Event Manager sends a copy of every event than an application sends to itself to the scripting component or other process that turned recording on.
The chapter “Introduction to Scripting” in this book provides an overview of how to make your application both scriptable and recordable. The chapter “Recording Apple Events” describes how to factor your application for recording and explains the Apple Event Manager’s recording mechanism.
Listing 4-0
Table 4-0
Responding to Apple Events
Contents
Handling Apple Events4-4
Accepting an Apple Event4-5
Installing Entries in the Apple Event Dispatch Tables4-7
Installing Entries for the Required Apple Events4-8
Installing Entries for Apple Events Sent by the Edition Manager4-9
How Apple Event Dispatching Works4-9
Handling the Required Apple Events4-11
Required Apple Events4-11
Handling the Open Application Event4-14
Handling the Open Documents Event4-15
Handling the Print Documents Event4-17
Handling the Quit Application Event4-19
Handling Apple Events Sent by the Edition Manager4-20
The Section Read, Section Write, and Section Scroll Events4-21
Handling the Create Publisher Event4-22
Getting Data Out of an Apple Event4-25
Getting Data Out of an Apple Event Parameter4-26
Getting Data Out of an Attribute4-28
Getting Data Out of a Descriptor List4-31
Writing Apple Event Handlers4-33
Replying to an Apple Event4-36
Disposing of Apple Event Data Structures4-39
Writing and Installing Coercion Handlers4-41
Interacting With the User4-45
Setting the Client Application’s User Interaction Preferences4-46
Setting the Server Application’s User Interaction Preferences4-48
Requesting User Interaction4-49
Reference to Responding to Apple Events4-56
Data Structures Used by the Apple Event Manager4-56
Descriptor Records and Related Data Structures4-56
Apple Event Array Data Types4-60
Routines for Responding to Apple Events4-61
Creating and Managing the Apple Event Dispatch Tables4-61
Dispatching Apple Events4-66
Getting Data or Descriptor Records Out of Apple Event Parameters and Attributes4-68
Counting the Items in Descriptor Lists4-74
Getting Items From Descriptor Lists4-74
Getting Data and Keyword-Specified Descriptor Records Out of AE Records4-78
Requesting User Interaction4-81
Requesting More Time to Respond to Apple Events4-84
Suspending and Resuming Apple Event Handling4-85
Getting the Sizes and Descriptor Types of Descriptor Records4-89
Deleting Descriptor Records4-92
Deallocating Memory for Descriptor Records4-93
Coercing Descriptor Types4-94
Creating and Managing the Coercion Handler Dispatch Tables4-96
Creating and Managing the Special Handler Dispatch Tables4-99
Getting Information About the Apple Event Manager4-103
Application-Defined Routines4-104
Summary of Responding to Apple Events4-108
Pascal Summary4-108
Constants4-108
Data Types4-112
Routines for Responding to Apple Events4-114
Application-Defined Routines4-118
C Summary4-118
Constants4-118
Data Types4-123
Routines for Responding to Apple Events4-124
Application-Defined Routines4-128
Assembly-Language Summary4-128
Trap Macros4-128
Result Codes4-130
Responding to Apple Events
This chapter describes how your application can use the Apple Event Manager to respond to Apple events. Your application must be able to respond to the four required Apple events to take advantage of the launching and terminating mechanisms that are part of System 7 and later versions of system software. If your application provides publish and subscribe capabilities, it should also handle the events sent by the Edition Manager. To be scriptable, or capable of responding to Apple events sent by scripting components, your application should handle the appropriate core and functional-area Apple events.
Before you read this chapter, you should be familiar with the chapters “Introduction to Interapplication Communication” and “Introduction to Apple Events” in this book. You should also have a copy of the Apple Event Registry: Standard Suites available for reference.
Although the Apple events used by the Edition Manager are discussed in this chapter, you must refer to the chapter “Edition Manager” in this book for a full discussion of how to implement the Edition Manager’s publish and subscribe features.
This chapter provides the basic information you need to make your application capable of responding to Apple events. To respond to core and functional-area Apple events, your application must also be able to resolve object specifier records. You should read the chapter “Resolving and Creating Object Specifier Records” before you write Apple event handlers for events that can contain object specifier records.
The section “Handling Apple Events,” which begins on page 4-4, describes how to
n accept and process Apple events
n install entries in the Apple event dispatch tables
n handle the required events
n handle events sent by the Edition Manager
n get data out of an Apple event
n write handlers that perform the action requested by an Apple event
n reply to an Apple event
n dispose of Apple event data structures
n write and install coercion handlers
The section “Interacting With the User,” which begins on page 4-45, describes
n how a server application can interact with the user when processing an Apple event
n how client applications set user interaction preferences
n how the client application’s preferences and the server application’s preferences affect user interaction
Handling Apple Events
You do not need to implement all Apple events at once. If you want to begin by supporting only the required Apple events, you must
n set bits in the 'SIZE' resource to indicate that your application supports high-level events
n include code to handle high-level events in your main event loop
n write routines that handle the required events
n install entries for the required Apple events in your application’s Apple event dispatch table
The following sections explain how to perform these tasks: “Accepting an Apple Event,” which begins on page 4-5, “Installing Entries in the Apple Event Dispatch Tables,” which begins on page 4-7, and “Handling the Required Apple Events,” which begins on page 4-11.
To respond to the Apple events sent by the Edition Manager in addition to the required events, you must install entries for the Section Read, Section Write, Section Scroll, and Create Publisher events in your application’s Apple event dispatch table and write the corresponding handlers, as described in “Handling Apple Events Sent by the Edition Manager” on page 4-20.
To respond to core and functional-area Apple events, you must install entries and write handlers for those events. You must also make sure that your application can locate Apple event objects with the aid of the Apple Event Manager routines described in the chapter “Resolving and Creating Object Specifier Records.” These routines are currently available as the Object Support Library (OSL), which you must link with your application when you build it.
The Apple Event Manager (excluding the OSL) is available only in System 7 and later versions of system software. Use the Gestalt function with the gestaltAppleEventsAttr selector to determine whether the Apple Event Manager is available. In the response parameter, the bit defined by the constant gestaltAppleEventsPresent is set if the Apple Event Manager is available.
gestaltAppleEventsPresent = 0; {if this bit is set, }
{ then the Apple Event }
{ Manager is available}
To find out which version of the Apple Event Manager is available, you can use the AEManagerInfo function; for more information, see page 4-104.
Accepting an Apple Event
To accept or send Apple events (or any other high-level events), you must set the appropriate flags in your application’s 'SIZE' resource and include code to handle high-level events in your application’s main event loop.
Two flags in the 'SIZE' resource determine whether an application receives high-level events:
n The isHighLevelEventAware flag must be set for your application to receive any high-level events.
n The localAndRemoteHLEvents flag must be set for your application to receive high-level events sent from another computer on the network.
Note that in order for your application to respond to Apple events sent from remote computers, the user of your application must also allow network users to link to your application. The user does this by selecting your application in the Finder, choosing Sharing from the File menu, and clicking the Allow Remote Program Linking checkbox. If the user has not yet started program linking, the Sharing command offers to display the Sharing Setup control panel so that the user can start program linking. The user must also authorize remote users for program linking by using the Users & Groups control panel. Program linking and setting up authenticated sessions are described in the chapter “Program-to-Program Communications Toolbox” in this book.
For a complete description of the 'SIZE' resource, see the chapter “Event Manager” in Inside Macintosh: Macintosh Toolbox Essentials.
Apple events (and other high-level events) are identified by a message class of kHighLevelEvent in the what field of the event record. You can test the what field of the event record to determine whether the event is a high-level event.
Listing 4-1 is an example of a procedure called from an application’s main event loop to handle events, including high-level events. The procedure determines the type of event received and then calls another routine to take the appropriate action.
Listing 4-1 A DoEvent procedure
PROCEDURE DoEvent (event: EventRecord);
BEGIN
CASE event.what OF {determine the type of event}
mouseDown:
DoMouseDown (event);
.
. {handle other kinds of events}
.
{handle high-level events, including Apple events}
kHighLevelEvent: DoHighLevelEvent (event);
END;
END;
Listing 4-2 is an example of a procedure that handles both Apple events and the high-level event identified by the event class mySpecialHLEventClass and the event ID mySpecialHLEventID. Note that, in most cases, you should use Apple events to communicate with other applications.
Listing 4-2 A DoHighLevelEvent procedure for handling Apple events and other high-level events
PROCEDURE DoHighLevelEvent (event: EventRecord);
VAR
myErr: OSErr;
BEGIN
IF (event.message = LongInt(mySpecialHLEventClass)) AND
{otherwise, assume that the event is an Apple event}
myErr := AEProcessAppleEvent(event);
{check and handle error}
IF myErr <> noErr THEN DoError(myErr);
END;
If your application accepts high-level events that do not follow the Apple Event Interprocess Messaging Protocol (AEIMP), you must dispatch these high-level events before calling AEProcessAppleEvent. To dispatch high-level events that do not follow AEIMP, you should check the event class, the event ID, or both for each event to see whether your application can handle the event.
After receiving a high-level event (and, if appropriate, checking whether it is a high-level event other than an Apple event), your application typically calls the AEProcessAppleEvent function. The AEProcessAppleEvent function determines the type of Apple event received, gets the event buffer that contains the parameters and attributes of the Apple event, and calls the corresponding Apple event handler in your application.
You should provide an Apple event handler for each Apple event that your application supports. This handler is responsible for performing the action requested by the Apple event and if necessary can return data in the reply Apple event.
If the client application requests a reply, the Apple Event Manager passes a default reply Apple event to your handler. If the client application does not request a reply, the Apple Event Manager passes a null descriptor record (a descriptor record of descriptor type typeNull and a data handle whose value is NIL) to your handler instead of a default reply Apple event.
After your handler finishes processing the Apple event and adds any parameters to the reply Apple event, it must return a result code to AEProcessAppleEvent. If the client application is waiting for a reply, the Apple Event Manager returns the reply Apple event to the client.
Installing Entries in the Apple Event Dispatch Tables
When your application receives an Apple event, use the AEProcessAppleEvent function to retrieve the data buffer of the event and to route the Apple event to the appropriate Apple event handler in your application. Your application supplies an Apple event dispatch table to map the Apple events your application supports to the Apple event handlers provided by your application.
To install entries in your application’s Apple event dispatch table, use the AEInstallEventHandler function. You usually install entries for all of the Apple events that your application accepts into your application’s Apple event dispatch table.
To install an Apple event handler in your Apple event dispatch table, you must specify
n the event class of the Apple event
n the event ID of the Apple event
n the address of the Apple event handler for the Apple event
n a reference constant
You provide this information to the AEInstallEventHandler function. In addition, you indicate whether the entry should be added to your application’s Apple event dispatch table or to the system Apple event dispatch table.
The system Apple event dispatch table is a table in the system heap that contains system Apple event handlers—handlers that are available to all applications and processes running on the same computer. The handlers in your application’s Apple event dispatch table are available only to your application. If AEProcessAppleEvent cannot find a handler for the Apple event in your application’s Apple event dispatch table, it looks in the system Apple event dispatch table for a handler (see
“How Apple Event Dispatching Works” on page 4-9 for details). If it doesn’t find a handler for the event, it returns the errAEEventNotHandled result code.
If you add a handler to the system Apple event dispatch table, the handler should reside in the system heap. If there was already an entry in the system Apple event dispatch table for the same event class and event ID, it is replaced unless you chain it to your system handler. See “Creating and Managing the Apple Event Dispatch Tables” on page 4-61 for details.
Installing Entries for the Required Apple Events
Listing 4-3 illustrates how to add entries for the required Apple events to your application’s Apple event dispatch table.
Listing 4-3 Adding entries for the required Apple events to an application’s Apple event dispatch table
myErr := AEInstallEventHandler(kCoreEventClass,
kAEOpenApplication,
@MyHandleOApp, 0, FALSE);
IF myErr <> noErr THEN DoError(myErr);
myErr := AEInstallEventHandler(kCoreEventClass,
kAEOpenDocuments,
@MyHandleODoc,0, FALSE);
IF myErr <> noErr THEN DoError(myErr);
myErr := AEInstallEventHandler(kCoreEventClass,
kAEPrintDocuments,
@MyHandlePDoc, 0, FALSE);
IF myErr <> noErr THEN DoError(myErr);
myErr := AEInstallEventHandler(kCoreEventClass,
kAEQuitApplication,
@MyHandleQuit, 0, FALSE);
IF myErr <> noErr THEN DoError(myErr);
The code in Listing 4-3 creates entries for all four required Apple events in the Apple event dispatch table. (For examples of handlers that correspond to these entries, see “Handling the Required Apple Events,” which begins on page 4-11.) The first entry creates an entry for the Open Application event. The entry indicates the event class and event ID of the Open Application event, supplies the address of the handler for that event, and specifies 0 as the reference constant.
The Apple Event Manager passes the reference constant to your handler each time your handler is called. Your application can use this reference constant for any purpose. If your application doesn’t use the reference constant, use 0 as the value.
The last parameter to the AEInstallEventHandler function is a Boolean value that determines whether the entry is added to the system Apple event dispatch table or to your application’s Apple event dispatch table. To add the entry to your application’s Apple event dispatch table, use FALSE as the value of this parameter. If you specify TRUE, the entry is added to the system Apple event dispatch table. The code shown in Listing 4-3 adds entries to the application’s Apple event dispatch table.
Installing Entries for Apple Events Sent by the Edition Manager
If your application supports the Edition Manager, you should also add entries to your application’s Apple event dispatch table for the Apple events that your application receives from the Edition Manager. Listing 4-4 shows how to add these entries.
Listing 4-4 Adding entries for Apple events sent by the Edition Manager to an application’s Apple event dispatch table
See “Handling Apple Events Sent by the Edition Manager” on page 4-20 for the parameters associated with these events. See the chapter “Edition Manager” in this book for information on how your application should respond to the Apple events sent by the Edition Manager.
How Apple Event Dispatching Works
In addition to the Apple event handler dispatch tables, applications can add entries to a special handler dispatch table in either the application heap or the system heap. These dispatch tables are used for various specialized handlers; for more information, see “Creating and Managing the Special Handler Dispatch Tables,” which begins on page 4-99.
When an application calls AEProcessAppleEvent, the function looks first in the application’s special handler dispatch table for an entry that was installed with the constant keyPreDispatch. If the application’s special handler dispatch table does not include such a handler or if the handler returns errAEEventNotHandled, the function looks in the application’s Apple event dispatch table for an entry that matches the event class and event ID of the specified Apple event.
If the application’s Apple event dispatch table does not include such a handler or if the handler returns errAEEventNotHandled, the AEProcessAppleEvent function looks in the system special handler dispatch table for an entry that was installed with the constant keyPreDispatch. If the system special handler dispatch table does not include such a handler or if the handler returns errAEEventNotHandled, the function looks in the system Apple event dispatch table for an entry that matches the event class and event ID of the specified Apple event.
If the system Apple event dispatch table does not include such a handler, the Apple Event Manager returns the result code errAEEventNotHandled to the server application and, if the client application is waiting for a reply, to the client application.
sWARNING
Before an application calls a system Apple event handler, system software has set up the A5 register for the calling application. For this reason, if you provide a system Apple event handler, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system handler may crash.s
For any entry in your Apple event dispatch table, you can specify a wildcard value for the event class, event ID, or both. You specify a wildcard by supplying the typeWildCard constant when installing an entry into the Apple event dispatch table. A wildcard value matches all possible values. Wildcards make it possible to supply one Apple event handler that dispatches several related Apple events.
For example, if you specify an entry with the typeWildCard event class and the kAEOpenDocuments event ID, the Apple Event Manager dispatches Apple events of any event class with an event ID of kAEOpenDocuments to the handler for that entry.
If you specify an entry with the kCoreEventClass event class and the typeWildCard event ID, the Apple Event Manager dispatches Apple events of the kCoreEventClass event class with any event ID to the handler for that entry.
If you specify an entry with the typeWildCard event class and the typeWildCard event ID, the Apple Event Manager dispatches all Apple events of any event class and any event ID to the handler for that entry.
If an Apple event dispatch table contains one entry for an event class and a specific event ID, and also contains another entry that is identical except that it specifies a wildcard value for either the event class or the event ID, the Apple Event Manager dispatches the more specific entry. For example, if an Apple event dispatch table includes one entry that specifies the event class as kAECoreSuite and the event ID as kAEDelete, and another entry that specifies the event class as kAECoreSuite and the event ID as typeWildCard, the Apple Event Manager will dispatch the Apple event handler associated with the entry that specifies the event ID as kAEDelete.
IMPORTANT
IMPORTANT
If your application sends Apple events to itself using a typeProcessSerialNumber address descriptor record with the lowLongOfPSN field set to kCurrentProcess, the Apple Event Manager jumps directly to the appropriate Apple event handler without going through the normal event-processing sequence. For this reason, your application will not appear to run more slowly when it sends Apple events to itself. For more information, see “Addressing an Apple Event for Direct Dispatching” on page 5-13.s
Handling the Required Apple Events
This section describes the required Apple events—the Apple events your application must support to be compatible with System 7 and later versions of system software—and the descriptor types for all parameters of the required Apple events. It also describes how to write the handlers for these events, and it provides sample code.
To support the required Apple events, you must set the necessary flags in the 'SIZE' resource of your application, install entries in your application’s Apple event dispatch table, add code to the event loop of your application to recognize high-level events, and call the AEProcessAppleEvent function, as described in “Accepting an Apple Event,” which begins on page 4-5, and “Installing Entries in the Apple Event Dispatch Tables,” which begins on page 4-7. You must also write handlers for each Apple event; this section describes how to write these handlers.
Required Apple Events
When a user opens or prints a file from the Finder, the Finder sets up the information your application uses to determine which files to open or print. In System 7 and later versions, if your application supports high-level events, the Finder communicates this information to your application through the required Apple events.
The Finder sends these required Apple events to your application to request the corresponding actions:
Apple event Requested action
Open Application Perform tasks your application normally performs when a user opens your application without opening or printing any documents
Open Documents Open the specified documents
Print Documents Print the specified documents
Quit Application Perform tasks—such as releasing memory, requesting the user to save documents, and so on—associated with quitting before the Finder terminates your application
In System 7 and later versions, the Finder uses these events as part of the mechanisms for launching and terminating applications. When the Finder launches your application, the application receives the Open Application, Open Documents, or Print Documents event. When the Finder terminates your application, the application receives the Quit Application event. This method of communicating Finder information to your application replaces the mechanisms used in earlier versions of system software.
Applications that do not support high-level events can still use the CountAppFiles, GetAppFiles, and ClrAppFiles procedures (or the GetAppParms procedure) to get the Finder information. See the chapter “Introduction to File Management” in Inside Macintosh: Files for information on these routines. To make your application compatible with System 7 and with earlier and later versions, you must support both the old and new mechanisms.
Use the Gestalt function to determine whether the Apple Event Manager is present. If it is and the isHighLevelEventAware flag is set in your application’s 'SIZE' resource, your application receives the Finder information through the required Apple events.
If your application accepts high-level events, it must be able to process the four required Apple events. Your application receives the required Apple events from the Finder in these situations:
n If your application is not open and the user opens your application from the Finder without opening or printing any documents, the Finder launches your application and sends it the Open Application event.
n If your application is not open and the user opens one of your application’s documents from the Finder, the Finder launches your application and sends it the Open Documents event.
n If your application is not open and the user prints one of your application’s documents from the Finder, the Finder launches your application and sends it the Print Documents event. Your application should print the selected documents and remain open until it receives a Quit Application event from the Finder.
n If your application is open and the user opens or prints any of your application’s documents from the Finder, the Finder sends your application the Open Documents or Print Documents event.
n If your application is open and the user chooses Restart or Shut Down from the Finder’s Special menu, the Finder sends your application the Quit Application event.
Upon receiving any of the required Apple events, your application should perform the action requested by the event. Here is a summary of the contents of the required events and the actions they request applications to perform:
Open Application—perform tasks associated with opening an application
Event class kCoreEventClass
Event ID kAEOpenApplication
Parameters None
Requested action Perform any tasks—such as opening an untitled document window—that you would normally perform when a user opens your application without opening or printing any documents.
Open Documents—open the specified documents
Event class kCoreEventClass
Event ID kAEOpenDocuments
Required parameter
Keyword: keyDirectObject
Descriptor type: typeAEList
Data: A list of alias records for the documents to be opened
Requested action Open the documents specified in the keyDirectObject parameter.
Print Documents—print the specified documents
Event class kCoreEventClass
Event ID kAEPrintDocuments
Required parameter
Keyword: keyDirectObject
Descriptor type: typeAEList
Data: A list of alias records for the documents to be printed
Requested action Print the documents specified in the keyDirectObject parameter without opening windows for the documents.
Quit Application—perform tasks associated with quitting(continued)
Event class kCoreEventClass
Event ID kAEQuitApplication
Parameters None
Requested action Perform any tasks that your application would normally perform when the user chooses Quit. Such tasks typically include asking the user whether to save documents that have been changed. When appropriate, the Finder sends this event to an application immediately after sending it a Print Documents event (unless the application was already open) or if the user chooses Restart or Shut Down from the Finder’s Special menu.
Your application needs to recognize only two descriptor types to handle the required Apple events: descriptor lists and alias records. The Open Documents event and Print Documents event use descriptor lists to store a list of documents to open. Each document is specified as an alias record in the descriptor list.
You can retrieve the data that specifies the document to open as an alias record, or you can request that the Apple Event Manager coerce the alias record to a file system specification (FSSpec) record. The file system specification record provides a standard method of identifying files in System 7 and later versions. See Inside Macintosh: Files for a complete description of how to specify files using file system specification records.
Handling the Open Application Event
When the user opens your application, the Finder uses the Process Manager to launch your application. On startup, your application typically performs any needed initialization, and then begins to process events. If your application supports high-level events, and if the user opens your application without selecting any documents to open or print, your application receives the Open Application event.
To handle the Open Application event, your application should do just what the user expects it to do when it is opened. For example, your application might open a new untitled window in response to an Open Application event.
Listing 4-5 shows a handler that processes the Open Application event. This handler first calls an application-defined function called MyGotRequiredParams, which checks whether the Apple event contains any required parameters. If so, the handler returns an error, because by definition, the Open Application event should not contain any required parameters. Otherwise, the handler opens a new document window.
Listing 4-5 A handler for the Open Application event
FUNCTION MyHandleOApp (theAppleEvent, reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myErr: OSErr;
BEGIN
myErr := MyGotRequiredParams(theAppleEvent);
IF myErr = noErr THEN
DoNew;
MyHandleOApp := myErr;
END;
For a description of the MyGotRequiredParams function, see Listing 4-11 on page 4-35. For information about the reply and handlerRefcon parameters for an Apple event handler, see “Writing Apple Event Handlers” on page 4-33.
Handling the Open Documents Event
To handle the Open Documents event, your application should open the documents that the Open Documents event specifies in its direct parameter. Your application extracts this information and then opens the specified documents. Listing 4-6 shows a handler for the Open Documents event.
Listing 4-6 A handler for the Open Documents event
FUNCTION MyHandleODoc (theAppleEvent, reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myFSS: FSSpec;
docList: AEDescList;
myErr, ignoreErr: OSErr;
index, itemsInList: LongInt;
actualSize: Size;
keywd: AEKeyword;
returnedType: DescType;
BEGIN
{get the direct parameter--a descriptor list--and put it }
{count the number of descriptor records in the list}
myErr := AECountItems (docList, itemsInList);
IF myErr = noErr THEN
{now get each descriptor record from the list, }
{ coerce the returned data to an FSSpec record, and }
{ open the associated file}
FOR index := 1 TO itemsInList DO
BEGIN
myErr := AEGetNthPtr(docList, index, typeFSS,
keywd, returnedType, @myFSS,
Sizeof(myFSS),actualSize);
IF myErr = noErr THEN
BEGIN
myErr := MyOpenFile(@myFSS);
IF myErr <> noErr THEN
; {handle error from MyOpenFile}
END
ELSE
; {handle error from AEGetNthPtr}
END; {of For index Do}
END
ELSE
; {handle error from MyGotRequiredParams}
ignoreErr := AEDisposeDesc(docList);
END
ELSE
; {failed to get direct parameter, handle error}
MyHandleODoc := myErr;
END;
The handler in Listing 4-6 first uses the AEGetParamDesc function to get the direct parameter (specified by the keyDirectObject keyword) out of the Apple event. The handler requests that AEGetParamDesc return a descriptor list in the docList variable. The handler then checks that it has retrieved all of the required parameters by calling the MyGotRequiredParams function. (See Listing 4-11 on page 4-35 for a description of this function.)
Once the handler has retrieved the descriptor list from the Apple event, it uses AECountItems to count the number of descriptors in the list. Using the returned number as an index, the handler can get the data of each descriptor record in the list. This handler requests that the AEGetNthPtr function coerce the data in the descriptor record to a file system specification record. The handler can then use the file system specification record as a parameter to its own routine for opening files.
For more information on the AEGetParamDesc function, see page 4-69. For more information on the AEGetNthPtr and AECountItems functions, see “Getting Data Out of a Descriptor List” on page 4-31.
After extracting the file system specification record that describes the document to open, your application can use this record to open the file. For example, in Listing 4-6, the code passes the file system specification record to its routine for opening files, the MyOpenFile function.
The MyOpenFile function should be designed so that it can be called in response to both the Open Documents event and to events generated by the user. For example, when the user chooses Open from the File menu, the code that handles the mouse-down event uses the StandardGetFile procedure to let the user choose a file; it then calls MyOpenFile, passing the file system specification record returned by StandardGetFile. By isolating code that performs a requested action from code that interacts with the user, you can easily adapt your application to handle Apple events that request the same action.
Note the use of the AEDisposeDesc function to dispose of the descriptor list when your handler no longer requires the data in it. Your handler should also return a result code.
Handling the Print Documents Event
To handle the Print Documents event, your application should extract information about the documents to be printed from the direct parameter, then print the specified documents.
If your application can interact with the user, it should open windows for the documents, display a Print dialog box for the first document, and use the settings entered by the user for the first document to print all the documents. If user interaction is not allowed, your application may either return the error errAENoUserInteraction or print the documents using default settings. See “Interacting With the User,” which begins on page 4-45, for information about using the AEInteractWithUser function to interact with the user.
Note that your application can remain open after processing the Print Documents event; when appropriate, the Finder sends your application a Quit Application event immediately after sending it a Print Documents event.
The handler for the Print Documents event shown in Listing 4-7 is similar to the handler for the Open Documents event, except that it prints the documents referred to in the direct parameter.
Listing 4-7 A handler for the Print Documents event
FUNCTION MyHandlePDoc (theAppleEvent, reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myFSS: FSSpec;
docList: AEDescList;
myErr, ignoreErr: OSErr;
index, itemsInList: LongInt;
actualSize: Size;
keywd: AEKeyword;
returnedType: DescType;
BEGIN
{get the direct parameter--a descriptor list--and put it }
{count the number of descriptor records in the list}
myErr := AECountItems (docList, itemsInList);
IF myErr = noErr THEN
{now get each descriptor record from the list, }
{ coerce the returned data to an FSSpec record, and }
{ print the associated file}
FOR index := 1 TO itemsInList DO
BEGIN
myErr := AEGetNthPtr(docList, index, typeFSS,
keywd, returnedType, @myFSS,
Sizeof(myFSS), actualSize);
IF myErr = noErr THEN
BEGIN
myErr := MyPrintFile(@myFSS);
IF myErr <> noErr THEN
; {handle error from MyOpenFile}
END
ELSE
; {handle error from AEGetNthPtr}
END; {of For index Do}
END
ELSE
; {handle error from MyGotRequiredParams}
ignoreErr := AEDisposeDesc(docList);
END
ELSE
; {failed to get direct parameter, handle error}
MyHandlePDoc := myErr;
END;
Handling the Quit Application Event
To handle the Quit Application event, your application should take any actions that are necessary before it is terminated (such as saving any open documents). Listing 4-8 shows an example of a handler for the Quit Application event.
When appropriate, the Finder sends your application a Quit Application event immediately after a Print Documents event. The Finder also sends your application a Quit Application event if the user chooses Restart or Shut Down from the Finder’s Special menu.
Listing 4-8 A handler for the Quit Application event
FUNCTION MyHandleQuit (theAppleEvent, reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myErr: OSErr;
userCanceled: Boolean;
BEGIN
{check for missing required parameters}
myErr := MyGotRequiredParams(theAppleEvent);
IF myErr = noErr THEN
BEGIN
userCanceled := MyPrepareToTerminate;
IF userCanceled THEN
MyHandleQuit := kUserCanceled
ELSE
MyHandleQuit := noErr;
END
ELSE
MyHandleQuit := myErr;
END;
The handler in Listing 4-8 calls another function supplied by the application, the MyPrepareToTerminate function. This function saves the documents for any open windows and returns a Boolean value that indicates whether the user canceled the Quit operation. This is another example of isolating code for interacting with the user from the code that performs the requested action. By structuring your application in this way, you can use the same routine to respond to a user action (such as choosing the Quit command from the File menu) or to the corresponding Apple event. (For a description of the MyGotRequiredParams function, see “Writing Apple Event Handlers” on page 4-33.)
IMPORTANT
When your application is ready to quit, it should call the ExitToShell procedure from the main event loop, not from your handler for the Quit Application event. Your application should quit only after the handler returns noErr as its function result.s
Handling Apple Events Sent by the Edition Manager
If your application provides publish and subscribe capabilities, it should handle the Apple events sent by the Edition Manager in addition to the required Apple events. Your application should also handle the Create Publisher event, which is described in the “Handling the Create Publisher Event” section on page 4-22.
The Edition Manager sends your application Apple events to communicate information about the publishers and subscribers in your application’s documents. Specifically, the Edition Manager uses Apple events to notify your application
n when the information in an edition is updated
n when your application needs to write the data from a publisher to an edition
n when your application should locate a particular publisher and scroll through the document to that location
The Section Read, Section Write, and Section Scroll Events
The following descriptions identify the three Apple events sent by the Edition Manager—Section Read, Section Write, and Section Scroll—and the actions they tell applications to perform.
Section Read—read information into the specified section (continued)
Event class SectionEventMsgClass
Event ID SectionReadMsgID
Required parameter
Keyword: keyDirectObject
Descriptor type: typeSectionH
Data: A handle to the section record of the subscriber whose edition contains updated information
Requested action Update the subscriber with the new information from the edition.
Section Write—write the specified section to an edition
Event class SectionEventMsgClass
Event ID SectionWriteMsgID
Required parameter
Keyword: keyDirectObject
Descriptor type: typeSectionH
Data: A handle to the section record of the publisher
Requested action Write the publisher’s data to its edition.
Section Scroll—scroll through the document to the specified section
Event class SectionEventMsgClass
Event ID SectionScrollMsgID
Required parameter
Keyword: keyDirectObject
Descriptor type: typeSectionH
Data: A handle to the section record of the publisher to scroll to
Requested action Scroll through the document to the publisher identified by the specified section record.
See the chapter “Edition Manager” in this book for details on how your application should respond to these events.
Handling the Create Publisher Event
If your application supports publish and subscribe capabilities, it should also handle the Create Publisher event.
Create Publisher—create a publisher
Event class kAEMiscStdSuite
Event ID kAECreatePublisher
Required parameter None
Optional parameter
Keyword: keyDirectObject
Descriptor type: typeObjectSpecifier
Data: An object specifier record that specifies the Apple event object or objects to publish. If this parameter is omitted, publish the current selection.
Optional parameter
Keyword: keyAEEditionFileLoc
Descriptor type: typeAlias
Data: An alias record that contains the location of the edition container to create. If this parameter is omitted, use the default edition container.
Requested action Create a publisher for the specified data using the specified loca-tion for the edition container. If the data isn’t specified, publish the current selection. If the location of the edition isn’t specified, use the default location.
When your application receives the Create Publisher event, it should create a publisher and write the publisher’s data to an edition. The data of the publisher, and the location and name of the edition, are defined by the Apple event. If the Create Publisher event includes a keyDirectObject parameter, then your application should publish the data contained in the parameter. If the keyDirectObject parameter is missing, then your application should publish the current selection. If the document doesn’t have a current selection, your handler for the event should return a nonzero result code.
If the Create Publisher event includes a keyAEEditionFileLoc parameter, your application should use the location and name contained in the parameter as the default location and name of the edition. If the keyAEEditionFileLoc parameter is missing, your application should use the default location and name your application normally uses to specify the edition container.
Listing 4-9 shows a handler for the Create Publisher event. This handler checks for the keyDirectObject parameter and the keyAEEditionFileLoc parameter. If either of these is not specified, the handler uses default values. The handler uses the application-defined function DoNewPublisher to create the publisher and its edition, create a section record, and update other data structures associated with the document. See the chapter “Edition Manager” in this book for an example of the DoNewPublisher function.
Listing 4-9 A handler for the Create Publisher event
FUNCTION MyHandleCreatePublisherEvent (theAppleEvent,
{add keyErrorNumber and keyErrorString parameters if desired}
END;
Note that the MyHandleCreatePublisherEvent handler in Listing 4-9 uses the AEInteractWithUser function to determine whether user interaction is allowed. If so, the handler sets the promptForDialog variable to TRUE, indicating that the DoNewPublisher function should display the publisher dialog box. If not,
the handler sets the promptForDialog variable to FALSE, and the DoNewPublisher function does not prompt the user for the location or name of the edition. For more information about AEInteractWithUser, see “Interacting With the User,” which begins on page 4-45.
Getting Data Out of an Apple Event
The Apple Event Manager stores the parameters and attributes of an Apple event in a format that is internal to the Apple Event Manager. You use Apple Event Manager functions to retrieve the data from an Apple event and return it to your application in a format your application can use.
Most of the functions that retrieve data from Apple event parameters and attributes are available in two forms: one that returns the desired data in a specified buffer and one that returns a descriptor record containing the same data. For example, the AEGetParamPtr function uses a specified buffer to return the data contained in an Apple event parameter, and the AEGetParamDesc function returns the descriptor record for a specified parameter.
You can also use Apple Event Manager functions to get data out of descriptor records, descriptor lists, and AE records. You use similar functions to put data into descriptor records, descriptor lists, and AE records.
When your handler receives an Apple event, you typically use the AEGetParamPtr, AEGetAttributePtr, AEGetParamDesc, or AEGetAttributeDesc function to get the data out of the Apple event.
Some Apple Event Manager functions let your application request that the data be returned using any descriptor type, even if it is different from the original descriptor type. If the original data is of a different descriptor type, the Apple Event Manager attempts to coerce the data to the requested descriptor type.
For example, the AEGetParamPtr function lets you specify the desired descriptor type of the resulting data as follows:
In this example, the desired type is specified in the third parameter by the typeLongInteger descriptor type. This requests that the Apple Event Manager coerce the data to a long integer if it is not already of this type. To prevent coercion and ensure that the descriptor type of the result is of the same type as the original, specify typeWildCard for the third parameter.
The Apple Event Manager returns, in the returnedType parameter, the descriptor type of the resulting data. This is useful information when you specify typeWildCard as the desired descriptor type; you can determine the descriptor type of the resulting data by examining this parameter.
The Apple Event Manager can coerce many different types of data. For example, the Apple Event Manager can convert alias records to file system specification records, integers to Boolean data types, and characters to numeric data types, in addition to other data type conversions. For a complete list of the data types for which the Apple Event Manager provides coercion handling, see Table 4-1 on page 4-43.
To perform data coercions that the Apple Event Manager doesn’t perform, you can provide your own coercion handlers. See “Writing and Installing Coercion Handlers,” which begins on page 4-41, for information on providing your own coercion handlers.
Apple event parameters are keyword-specified descriptor records. You can use AEGetParamDesc to get the descriptor record of a parameter, or you can use AEGetParamPtr to get the data out of the descriptor record of a parameter. If an Apple event parameter consists of an object specifier record, you can use AEResolve and your own object accessor functions to resolve the object specifier record—that is, to locate the Apple event object it describes. For more information about AEResolve and object accessor functions, see “Writing Object Accessor Functions,” which begins on page 6-28. Attributes are also keyword-specified descriptor records, and you can use similar routines to get the descriptor record of an attribute or to get the data out of an attribute.
The following sections show how to use the AEGetParamPtr, AEGetAttributePtr, AEGetParamDesc, or AEGetAttributeDesc function to get the data out of an Apple event.
Getting Data Out of an Apple Event Parameter
You can use the AEGetParamPtr or AEGetParamDesc function to get the data out of an Apple event parameter. Use the AEGetParamPtr function (or the AEGetKeyPtr function, which works the same way) to return the data contained in a parameter. Use the AEGetParamDesc function when you need to get the descriptor record of a parameter or to extract the descriptor list from a parameter.
For example, suppose you need to get the data out of a Section Read event. The Edition Manager sends your application a Section Read event to tell your application to read updated information from an edition into the specified subscriber. The direct parameter of the Apple event contains a handle to the section record of the subscriber. You can use the AEGetParamPtr function to get the data out of the Apple event.
You specify the Apple event that contains the desired parameter, the keyword of the desired parameter, the descriptor type the function should use to return the data, a buffer to store the data, and the size of this buffer as parameters to the AEGetParamPtr function. The AEGetParamPtr function returns the descriptor type of the resulting data and the actual size of the data, and it places the requested data in the specified buffer.
In this example, the keyDirectObject keyword specifies that the AEGetParamPtr function should extract information from the direct parameter; AEGetParamPtr returns the data in the buffer specified by the sectionH variable.
You can request that the Apple Event Manager return the data using the descriptor type of the original data or you can request that the Apple Event Manager coerce the data into a descriptor type that is different from the original. To prevent coercion, specify the desired descriptor type as typeWildCard.
The typeSectionH descriptor type specifies that the returned data should be coerced to a handle to a section record. You can use the information returned in the sectionH variable to identify the subscriber and read in the information from the edition.
In this example, the AEGetParamPtr function returns, in the returnedType variable, the descriptor type of the resulting data. The descriptor type of the resulting data matches the requested descriptor type unless the Apple Event Manager wasn’t able to coerce the data to the specified descriptor type or you specified the desired descriptor type as typeWildCard. If the coercion fails, the Apple Event Manager returns the errAECoercionFail result code.
The AEGetParamPtr function returns, in the actualSize variable, the actual size of the data (that is, the size of coerced data, if any coercion was performed). If the value returned in this variable is greater than the amount your application allocated for the buffer to hold the returned data, your application can increase the size of its buffer to this amount, and get the data again. You can also choose to use the AEGetParamDesc function when your application doesn’t know the size of the data.
In general, use the AEGetParamPtr function to extract data that is of fixed length or known maximum length, and the AEGetParamDesc function to extract data that is of variable length. The AEGetParamDesc function returns the descriptor record for an Apple event parameter. This function is useful, for example, for extracting a descriptor list from a parameter.
You specify, as parameters to AEGetParamDesc, the Apple event that contains the desired parameter, the keyword of the desired parameter, the descriptor type the function should use to return the descriptor record, and a buffer to store the returned descriptor record. The AEGetParamDesc function returns the descriptor record using the specified descriptor type.
For example, the direct parameter of the Open Documents event contains a descriptor list that specifies the documents to open. You can use the AEGetParamDesc function to get the descriptor list out of the direct parameter.
In this example, the Apple event specified by the variable theAppleEvent contains the desired parameter. The keyDirectObject keyword specifies that the AEGetParamDesc function should get the descriptor record of the direct parameter. The typeAEList descriptor type specifies that the descriptor record should be returned as a descriptor list. In this example, the AEGetParamDesc function returns a descriptor list in the docList variable.
The descriptor list contains a list of descriptor records. To get the descriptor records and their data out of a descriptor list, use the AECountItems function to find the number of descriptor records in the list and then make repetitive calls to the AEGetNthPtr function to get the data out of each descriptor record. See “Getting Data Out of a Descriptor List” on page 4-31 for more information.
Note that the AEGetParamDesc function copies the descriptor record from the parameter. When you’re done with a descriptor record that you obtained from AEGetParamDesc, you must dispose of it by calling the AEDisposeDesc function.
If an Apple event parameter consists of an object specifier record, you can use AEResolve to resolve the object specifier record (that is, locate the Apple event object it describes), as explained in “Finding Apple Event Objects” on page 3-46.
Getting Data Out of an Attribute
You can use the AEGetAttributePtr or AEGetAttributeDesc function to get the data out of the attributes of an Apple event.
You specify, as parameters to AEGetAttributePtr, the Apple event that contains the desired attribute, the keyword of the desired attribute, the descriptor type the function should use to return the data, a buffer to store the data, and the size of this buffer. The AEGetAttributePtr function returns the descriptor type of the returned data and the actual size of the data and places the requested data in the specified buffer.
For example, this code gets the data out of the keyEventSourceAttr attribute of an Apple event.
The keyEventSourceAttr keyword specifies the attribute from which to get the data. The typeShortInteger descriptor type specifies that the data should be returned as a short integer; the returnedType variable contains the actual descriptor type that is returned. You also must specify a buffer to hold the returned data and specify the size of this buffer. If the data is not already a short integer, the Apple Event Manager coerces it as necessary before returning it. The AEGetAttributePtr function returns, in the actualSize variable, the actual size of the returned data after coercion has taken place. You can check this value to make sure you got all the data.
As with the AEGetParamPtr function, you can request that AEGetAttributePtr return the data using the descriptor type of the original data, or you can request that the Apple Event Manager coerce the data into a descriptor type that is different from the original.
In this example, the AEGetAttributePtr function returns the requested data as a short integer in the sourceOfAE variable, and you can get information about the source of the Apple event by examining this value. You can test the returned value against the values defined by the data type AEEventSource.
TYPE AEEventSource = (kAEUnknownSource, kAEDirectCall,
kAESameProcess, kAELocalProcess,
kAERemoteProcess);
The constants defined by the data type AEEventSource have the following meanings:
Constant Meaning
kAEUnknownSource Source of Apple event unknown
kAEDirectCall A direct call that bypassed the PPC Toolbox
kAESameProcess Target application is also the source application
kAELocalProcess Source application is another process on the same computer as the target application
kAERemoteProcess Source application is a process on a remote computer on the network
The next example shows how to use the AEGetAttributePtr function to get data out of the keyMissedKeywordAttr attribute. After your handler extracts all known parameters from an Apple event, it should check whether the keyMissedKeywordAttr attribute exists. If it does, then your handler did not get all of the required parameters.
Note that if AEGetAttributePtr returns the errAEDescNotFound result code, then the keyMissedKeywordAttr attribute does not exist—that is, your application has extracted all of the required parameters. If AEGetAttributePtr returns noErr, then the keyMissedKeywordAttr attribute does exist—that is, your handler did not get all of the required parameters.
The data in the keyMissedKeywordAttr attribute contains the keyword of the first required parameter, if any, that your handler didn’t retrieve. If you want this data returned, specify a buffer to hold it and specify the buffer size. Otherwise, as in this example, specify NIL as the buffer and 0 as the size of the buffer.
This example shows how to use the AEGetAttributePtr function to get the address of the sender of an Apple event from the keyAddressAttr attribute of the Apple event:
The keyAddressAttr keyword specifies the attribute to get the data from. The typeTargetID descriptor type specifies that the data should be returned as a target ID record; the returnedType variable contains the actual descriptor type that is returned. You can examine the address returned in the addressOfAE variable to determine the sender of the Apple event.
The target ID record returned in the addressOfAE variable contains the sender’s port name, port location, and session reference number. To get the process serial number for a process on the local machine, pass the port name returned in the target ID record to the GetProcessSerialNumberFromPortName function. You can then pass the process serial number to the GetProcessInformation function to find the creator signature for a given process. (For more information about these functions, see the chapter “Event Manager” in Inside Macintosh: Macintosh Toolbox Essentials.)
For more information about target addresses, see “Specifying a Target Address” on page 5-10.
Getting Data Out of a Descriptor List
You can use the AECountItems function to count the number of items in a descriptor list, and you can use AEGetNthDesc or AEGetNthPtr to get a descriptor record or its data out of a descriptor list.
The Open Documents event contains a direct parameter that specifies the list of documents to open. The list of documents is contained in a descriptor list. After extracting the descriptor list from the parameter, you can determine the number of items in the list and then extract each descriptor record from the descriptor list. See Figure 3-9 on page 3-19 for a depiction of the Open Documents event.
For example, when your handler receives an Open Documents event, you can use the AEGetParamDesc function to return the direct parameter as a descriptor list. You can then use AECountItems to return the number of descriptor records in the list.
The AEGetParamDesc function returns, in the docList variable, a copy of the descriptor list from the direct parameter of the Open Documents event. You specify this list to the AECountItems function.
You specify the descriptor list whose items you want to count in the first parameter to AECountItems. The Apple Event Manager returns, in the second parameter, the number of items in the list. When extracting the descriptor records from a list, you often use the number of items as a loop index. Here’s an example:
FOR index := 1 TO itemsInList DO
BEGIN
{for each descriptor record in the list, get its data}
END;
The format of the descriptor records in a descriptor list is private to the Apple Event Manager. You must use the AEGetNthPtr or AEGetNthDesc function to extract descriptor records from a descriptor list.
You specify the descriptor list that contains the desired descriptor records and an index as parameters to the AEGetNthPtr function. The index represents a specific descriptor record in the descriptor list. The AEGetNthPtr function returns the data for the descriptor record represented by the specified index.
You also specify the descriptor type the function should use to return the data, a buffer to store the data, and the size of this buffer. If the specified descriptor record exists, the AEGetNthPtr function returns the keyword of the parameter, the descriptor type of the returned data, and the actual size of the data, and it places the requested data in the specified buffer.
Here’s an example that uses the AEGetNthPtr function to extract an item from the descriptor list in the direct parameter of the Open Documents event:
The docList variable specifies the descriptor list from the direct parameter of the Open Documents event. The index variable specifies the index of the descriptor record to extract. You can use the typeFSS descriptor type, as in this example, to specify that the data be returned as a file system specification record. The Apple Event Manager automatically coerces the original data type of the descriptor record from an alias record to a file system specification record. The AEGetNthPtr function returns the keyword of the parameter and the descriptor type of the resulting data in the keywd and returnedType variables, respectively.
You also specify a buffer to hold the desired data and the size (in bytes) of the buffer. In this example, the myFSS variable specifies the buffer. The function returns the actual size of the data in the actualSize variable. If this size is larger than the size of the buffer you provided, you know that you didn’t get all of the data for the descriptor record.
Listing 4-10 shows a more complete example of extracting the items from a descriptor list in the Open Documents event.
Listing 4-10 Extracting items from a descriptor list
For each Apple event your application supports, you must provide a function called an Apple event handler. The AEProcessAppleEvent function calls one of your Apple event handlers when it processes an Apple event. Your Apple event handlers should perform any action requested by the Apple event, add parameters to the reply Apple event if appropriate, and return a result code.
The Apple Event Manager uses dispatch tables to route Apple events to the appropriate Apple event handler. You must supply an Apple event handler for each entry in your application’s Apple event dispatch table. Each handler must be a function that uses this syntax:
FUNCTION MyEventHandler (theAppleEvent: AppleEvent;
reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
The parameter theAppleEvent is the Apple event to handle. Your handler uses Apple Event Manager functions to extract any parameters and attributes from the Apple event and then performs the necessary processing. If any of the parameters include object specifier records, your handler should call AEResolve to resolve them—that is, to locate the Apple event objects they describe. For more information, see the chapter “Resolving and Creating Object Specifier Records” in this book.
The reply parameter is the default reply provided by the Apple Event Manager. (“Replying to an Apple Event,” which begins on page 4-36, describes how to add parameters to the default reply.) The handlerRefcon parameter is the reference constant stored in the Apple event dispatch table entry for the Apple event. Your handler can check the reference constant, if necessary, for information about the Apple event.
You can use the reference constant for anything you wish. For example, if you want to use the same handler for several Apple events, you can install entries for each event in your application’s Apple event dispatch table that specify the same handler but different reference constants. Your handler can then use the reference constant to distinguish the different Apple events it handles.
To provide an Apple event handler in C, be sure to include the Pascal declaration before the handler declaration. This is the syntax for an Apple event handler in C:
After extracting all known parameters from the Apple event, every handler should determine whether the Apple event contains any further required parameters. Your handler can determine whether it retrieved all the required parameters by checking whether the keyMissedKeywordAttr attribute exists. If the attribute exists, then your handler has not retrieved all the required parameters and should immediately return an error. If the attribute does not exist, then the Apple event does not contain any more required parameters, although it may contain additional optional parameters.
The Apple Event Manager determines which parameters are optional according to the keywords listed in the keyOptionalKeywordAttr attribute. The source application is responsible for adding these keywords to the keyOptionalKeywordAttr attribute, but is not required to do so, even if that parameter is listed in the Apple Event Registry: Standard Suites as an optional parameter. If the source application does not add the necessary keyword to the keyOptionalKeywordAttr attribute, the target application treats the parameter as required for that Apple event. If the target application supports the parameter, it should handle the Apple event as the source application expects. If the target application does not support the parameter and checks whether it has received all the required parameters, it finds that there’s another parameter that the client application considered required, and should return the result code errAEParamMissed without attempting to handle the event.
Listing 4-11 shows a function that checks for a keyMissedKeywordAttr attribute. A handler calls this function after getting all the required parameters it knows about from an Apple event.
Listing 4-11 A function that checks for a keyMissedKeywordAttr attribute
FUNCTION MyGotRequiredParams (theAppleEvent: AppleEvent): OSErr;
VAR
myErr: OSErr;
returnedType: DescType;
actualSize: Size;
BEGIN
myErr := AEGetAttributePtr(theAppleEvent,
keyMissedKeywordAttr,
typeWildCard, returnedType,
NIL, 0, actualSize);
IF myErr = errAEDescNotFound THEN
{you got all the required parameters}
MyGotRequiredParams := noErr
ELSE IF myErr = noErr THEN
{you missed a required parameter}
MyGotRequiredParams := errAEParamMissed;
END;
The code in Listing 4-11 uses the AEGetAttributePtr function to get the keyMissedKeywordAttr attribute. This attribute contains the first required parameter, if any, that your handler didn’t retrieve. If AEGetAttributePtr returns the errAEDescNotFound result code, the Apple event doesn’t contain a keyMissedKeywordAttr attribute. If the Apple event doesn’t contain this attribute, then your handler has extracted all of the parameters that the client application considered required.
If the AEGetAttributePtr function returns noErr as the result code, then the attribute does exist, meaning that your handler has not extracted all of the required parameters. In this case, your handler should return an error and not process the Apple event.
The first remaining required parameter is specified by the data of the keyMissedKeywordAttr attribute. If you want this data returned, specify a buffer to hold the data. Otherwise, specify NIL as the buffer and 0 as the size of the buffer. If you specify a buffer to hold the data, you can check the value of the actualSize parameter to see if the data is larger than the buffer you allocated.
For more information about specifying Apple event parameters as optional or required, see “Specifying Optional Parameters for an Apple Event” beginning on page 5-7.
Replying to an Apple Event
Your handler routine for a particular Apple event is responsible for performing the action requested by the Apple event, and can optionally return data in a reply Apple event. The Apple Event Manager passes a default reply Apple event to your handler. The default reply Apple event has no parameters when it is passed to your handler. Your handler can add parameters to the reply Apple event. If the client application requested a reply, the Apple Event Manager returns the reply Apple event to the client.
The reply Apple event is identified by the kCoreEventClass event class and by the kAEAnswer event ID. If the client application specified the kAENoReply flag in the reply parameter of the AESend function, the Apple Event Manager passes a null descriptor record (a descriptor record of type typeNull whose data handle has the value NIL) to your handler instead of a default reply Apple event. Your handler should check the descriptor type of the reply Apple event before attempting to add any attributes or parameters to it. An attempt to add an Apple event attribute or parameter to a null descriptor record generates an error.
If the client application requests a reply, the Apple Event Manager prepares a reply Apple event for the client by passing a default reply Apple event to your handler. The default reply Apple event has no parameters when it is passed to your handler. Your handler can add any parameters to the reply Apple event. If your application is a spelling checker, for example, you can return a list of misspelled words in a parameter.
When your handler finishes processing an Apple event, it returns a result code to AEProcessAppleEvent, which returns this result code as its function result. If your handler returns a nonzero result code, and if you have not added your own keyErrorNumber parameter, the Apple Event Manager also returns this result code to the client application by putting the result code into a keyErrorNumber parameter for the reply Apple event. The client can check for the existence of this parameter to determine whether the handler performed the requested action.
The client application specifies whether it wants a reply Apple event or not by specifying flags (represented by constants) in the sendMode parameter of the AESend function.
If the client specifies the kAEWaitReply flag in the sendMode parameter, the AESend function does not return until the timeout specified by the timeoutInTicks parameter expires or the server application returns a reply. When the server application returns a reply, the reply parameter to AESend contains the reply Apple event that your handler returned to the AEProcessAppleEvent function. When the client application no longer needs the original Apple event and the reply event, it must dispose of them, but the Apple Event Manager disposes of both the Apple event and the reply event for the server application when the server’s handler returns to AEProcessAppleEvent.
If the client specified the kAEQueueReply flag, the client receives the reply event at a later time during its normal processing of other events.
Your handler should always set its function result to noErr if it successfully
handles the Apple event. If an error occurs, your handler should return either errAEEventNotHandled or some other nonzero result code. If the error
occurs because your application cannot understand the event, return errAEEventNotHandled. This allows the Apple Event Manager to look for a handler in the system special handler or system Apple event dispatch tables that might be able to handle the event. If the error occurs because the event is impossible to handle as specified, return the result code returned by whatever function caused the failure, or whatever other result code is appropriate.
For example, suppose your application receives a Get Data event requesting the name of the current printer, and your application cannot handle such an event. In this situation, you should return errAEEventNotHandled in case another handler available to the Apple Event Manager can handle the Get Data event. This strategy allows users to take advantage of system capabilities from within your application via system handlers.
However, if your application cannot handle a Get Data event that requests the fifth paragraph in a document because the document contains only four paragraphs, you should return some other nonzero error, because further attempts to handle the event are pointless.
If your Apple event handler calls the AEResolve function and AEResolve calls an object accessor function in the system object accessor dispatch table, your Apple event handler may not recognize the descriptor type of the token returned by the function. In this case, your handler should return the result code errAEUnknownObjectType. When your handler returns this result code, the Apple Event Manager attempts to locate a system Apple event handler that can recognize the token. For more information, see “Installing Entries in the Object Accessor Dispatch Tables,” which begins on page 6-21.
The Apple Event Manager automatically adds any nonzero result code that your handler returns to a keyErrorNumber parameter in the reply Apple event. In addition to returning a result code, your handler can also return an error string in the keyErrorString parameter of the reply Apple event. Your handler should provide meaningful text in the keyErrorString parameter, so that the client can display this string to the user if desired.
Listing 4-12 shows how to add the keyErrorString parameter to the reply Apple event. See “Adding Parameters to an Apple Event” on page 5-5 for a description of the AEPutParamPtr function.
Listing 4-12 Adding the keyErrorString parameter to the reply Apple event
FUNCTION MyHandler (theAppleEvent: AppleEvent; reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myErr: OSErr;
errStr: Str255;
BEGIN
{handle your Apple event here}
{if an error occurs when handling an Apple event, set the }
{ function result and error string accordingly}
IF myErr <> noErr THEN
BEGIN
MyHandler := myErr; {result code to be returned--the }
{ Apple Event Manager adds this }
{ result code to the reply Apple }
{ event as the keyErrorNumber }
{ parameter}
IF (reply.dataHandle <> NIL) THEN
{add error string parameter to the default reply}
BEGIN
{strings should normally be stored in resources}
errStr := 'Why error occurred';
myErr := AEPutParamPtr(reply, keyErrorString,
typeIntlText, @errStr[1],
length(errStr));
END;
END
ELSE
MyHandler := noErr;
END;
If your handler needs to return data to the client, it can add parameters to the reply Apple event. Listing 4-13 shows how a handler for the Multiply event (an imaginary Apple event that asks the server to multiply two numbers) might return the results of the multiplication to the client.
Listing 4-13 Adding parameters to the reply Apple event
FUNCTION MyMultHandler (theAppleEvent: AppleEvent;
reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myErr: OSErr;
number1,number2: LongInt;
replyResult: LongInt;
actualSize: Size;
returnedType: DescType;
BEGIN
{get the numbers to multiply from the parameters of the }
{ Apple event; put the numbers in the number1 and number2 }
{ variables and then perform the requested multiplication}
myErr := MyDoMultiply(theAppleEvent, number1,
number2, replyResult);
IF myErr = noErr THEN
IF (reply.dataHandle <> NIL) THEN
{return result of the multiplication in the reply Apple }
{ event}
myErr := AEPutParamPtr(reply, keyDirectObject,
typeLongInteger, @replyResult,
SizeOf(replyResult));
MyMultHandler := myErr;
{if an error occurs, set the error string }
{ accordingly, as shown in Listing 4-12}
END;
Disposing of Apple Event Data Structures
Whenever a client application uses Apple Event Manager functions to create a descriptor record, descriptor list, or Apple event record, the Apple Event Manager allocates memory for these data structures in the client’s application heap. Likewise, when a server application extracts a descriptor record from an Apple event by using Apple Event Manager functions, the Apple Event Manager creates a copy of the descriptor record, including the data to which its handle refers, in the server’s application heap.
Whenever you finish using a descriptor record or descriptor list that you have created or extracted from an Apple event, you should dispose of the descriptor record—and thereby deallocate the memory it uses—by calling the AEDisposeDesc function. If the descriptor record you pass to AEDisposeDesc (such as an Apple event record or an AE record) includes other nested descriptor records, one call to AEDisposeDesc will dispose of them all.
When a client application adds a descriptor record to an Apple event (for example, when it creates a descriptor record by calling AECreateDesc and then puts a copy of it into a parameter of an Apple event by calling AEPutParamDesc), it is still responsible for disposing of the original descriptor record. After a client application has finished using both the Apple event specified in the AESend function and the reply Apple event, it should dispose of their descriptor records by calling AEDisposeDesc. The client application should dispose of them even if AESend returns a nonzero result code.
The Apple event that a server application’s handler receives is a copy of the original event created by the client application. When a server application’s handler returns to AEProcessAppleEvent, the Apple Event Manager disposes of the server’s copy (in the server’s application heap) of both the Apple event and the reply event. The server application is responsible for disposing of any descriptor records created while extracting data from the Apple event or adding data to the reply event.
In general, outputs from Apple Event Manager functions are your application’s responsibility. Once you finish using them, you should use AEDisposeDesc to dispose of any Apple event data structures created or returned by these functions:AECoerceDesc AEDuplicateDesc
AECoercePtr AEGetAttributeDesc
AECreateAppleEvent AEGetKeyDesc
AECreateDesc AEGetNthDesc
AECreateList AEGetParamDesc
If you attempt to dispose of descriptor records returned by successful calls to these functions without using AEDisposeDesc, your application may not be compatible with future versions of the Apple Event Manager. However, if any of these functions return a nonzero result code, they return a null descriptor record, which does not need to be disposed of.
Outputs from functions, such as AEGetKeyPtr, that use a buffer rather than a descriptor record to return data do not require the use of AEDisposeDesc. It is therefore preferable to use these functions for any data that is not identified by a handle.
Some of the functions described in the chapter “Resolving and Creating Object Specifier Records” in this book also create descriptor records. If you set the disposeInputs parameter to FALSE for any of the following functions, you should dispose of any Apple event data structures that they create or return:CreateCompDescriptor CreateObjSpecifier
CreateLogicalDescriptor CreateRangeDescriptor
Your application is also responsible for disposing of some of the tokens it creates in the process of resolving an object specifier record. For information about token disposal, see “Defining Tokens” on page 6-39.
Writing and Installing Coercion Handlers
When your application extracts data from a parameter, it can request that the Apple Event Manager return the data using a descriptor type that is different from the original descriptor type. For example, when extracting data from the direct parameter of the Open Documents event, you can request that the alias records be returned as file system specification records. The Apple Event Manager can automatically coerce many different types of data from one to another. Table 4-1 on page 4-43 shows descriptor types and the kinds of coercion that the Apple Event Manager can perform.
You can also provide your own routines, referred to as coercion handlers, to coerce data into any other descriptor type. To install your own coercion handlers, use the AEInstallCoercionHandler function. You specify as parameters to this function
n the descriptor type of the data coerced by the handler
n the descriptor type of the resulting data
n the address of the coercion handler for this descriptor type
n a reference constant
n a Boolean value that indicates whether your coercion handler expects the data to be specified as a descriptor record or as a pointer to the actual data
n a Boolean value that indicates whether your coercion handler should be added to your application’s coercion dispatch table or the system coercion dispatch table
The system coercion dispatch table is a table in the system heap that contains coercion handlers available to all applications and processes running on the same computer. The coercion handlers in your application’s coercion dispatch table are available only to your application. When attempting to coerce data, the Apple Event Manager first looks for a coercion handler in your application’s coercion dispatch table. If it cannot find a handler for the descriptor type, it looks in the system coercion dispatch table for a handler. If it doesn’t find a handler there, it attempts to use the default coercion handling described by Table 4-1 on page 4-43. If it can’t find an appropriate default coercion handler, it returns the errAECoercionFail result code.
Any handler that you add to the system coercion dispatch table should reside in the system heap. If there was already an entry in the system coercion dispatch table for the same descriptor type, it is replaced. Therefore, if there is an entry in the system coercion dispatch table for the same descriptor type, you should chain it to your system coercion handler as explained in “Creating and Managing the Coercion Handler Dispatch Tables,” which begins on page 4-96.
sWARNING
Before an application calls a system coercion handler, system software has set up the A5 register for the calling application. For this reason, if you provide a system coercion handler, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system coercion handler may crash.s
You can provide a coercion handler that expects to receive the data in a descriptor record or a buffer referred to by a pointer. When you install your coercion handler, you specify how your handler wishes to receive the data. Whenever possible, you should write your coercion handler so that it can accept a pointer to the data, because it’s more efficient for the Apple Event Manager to provide your coercion handler with a pointer to the data.
A coercion handler that accepts a pointer to data must be a function with the following syntax:
FUNCTION MyCoercePtr (typeCode: DescType; dataPtr: Ptr;
dataSize: Size; toType: DescType;
handlerRefcon: LongInt;
VAR result: AEDesc): OSErr;
The typeCode parameter is the descriptor type of the original data. The dataPtr parameter is a pointer to the data to coerce; the dataSize parameter is the length, in bytes, of the data. The toType parameter is the desired descriptor type of the resulting data. The handlerRefcon parameter is a reference constant stored in the coercion table entry for the handler and passed to the handler by the Apple Event Manager whenever the handler is called. The result parameter is the descriptor record returned by your coercion handler.
Your coercion handler should coerce the data to the desired descriptor type and return the data in the descriptor record specified by the result parameter. If your handler successfully performs the coercion, it should return the noErr result code; otherwise, it should return a nonzero result code.
A coercion handler that accepts a descriptor record must be a function with the following syntax:
FUNCTION MyCoerceDesc (theAEDesc: AEDesc; toType: DescType;
handlerRefcon: LongInt;
VAR result: AEDesc): OSErr;
The parameter theAEDesc is the descriptor record that contains the data to be coerced. The toType parameter is the descriptor type of the resulting data. The handlerRefcon parameter is a reference constant stored in the coercion table entry for the handler and passed to the handler by the Apple Event Manager whenever the handler is called. The result parameter is the resulting descriptor record.
Your coercion handler should coerce the data in the descriptor record to the desired descriptor type and return the data in the descriptor record specified by the result parameter. Your handler should return an appropriate result code.
Note
To ensure that no coercion is performed and that the descriptor type of the result is of the same descriptor type as the original, specify typeWildCard for the desired type.u
Table 4-1 lists the descriptor types for which the Apple Event Manager provides coercion.
Table 4-1 Coercion handling provided by the Apple Event Manager(continued)
Original descriptor type of data to be coerced Desired descriptor type Description
typeChar typeIntegertypeLongIntegertypeSMInttypeSMFloattypeShortIntegertypeFloattypeLongFloattypeShortFloattypeExtendedtypeComptypeMagnitude Any string that is a valid representation of a number can be coerced into an equivalent numeric value.
typeIntegertypeLongInteger typeSMInttypeSMFloattypeShortIntegertypeFloattypeLongFloattypeShortFloattypeExtendedtypeComptypeMagnitude typeChar Any numeric descriptor type can be coerced into the equivalent text string.
typeIntegertypeLongInteger typeSMInttypeSMFloattypeShortInteger typeFloattypeLongFloattypeShortFloattypeExtendedtypeComptypeMagnitude typeIntegertypeLongIntegertypeSMInttypeSMFloattypeShortIntegertypeFloattypeLongFloattypeShortFloattypeExtendedtypeComptypeMagnitude Any numeric descriptor type can be coerced into any other numeric descriptor type.
typeChar typeTypetypeEnumeratedtypeKeyword
typeProperty Any four-character string can be coerced to one of these descriptor types.
typeEnumeratedtypeKeywordtypePropertytypeType typeChar Any of these descriptor types can be coerced to the equivalent text string.
continued
typeIntlText typeChar The result contains text only, without the script code or language code from the original descriptor record.
typeTrue typeBoolean The result is the Boolean value TRUE.
typeFalse typeBoolean The result is the Boolean value FALSE.
typeEnumerated typeBoolean The enumerated value 'true' becomes the Boolean value TRUE. The enumerated value 'fals' becomes the Boolean value FALSE.
typeBoolean typeEnumerated The Boolean value FALSE becomes the enumerated value 'fals'. The Boolean value TRUE becomes the enumerated value 'true'.
typeShortInteger
typeSMInt typeBoolean A value of 1 becomes the Boolean value TRUE. A value of 0 becomes the Boolean value FALSE.
typeBoolean typeShortInteger typeSMInt A value of FALSE becomes 0. A value of TRUE becomes 1.
typeAlias typeFSS An alias record is coerced into a file system specification record.
typeAppleEvent typeAppParameters An Apple event is coerced into a list of application parameters for the LaunchParamBlockRec parameter block.
any descriptor type typeAEList A descriptor record is coerced into a descriptor list containing a single item.
typeAEList type of list item A descriptor list containing a single descriptor record is coerced into a descriptor record.
NOTESome of the descriptor types listed in this table are synonyms; for example, the constants typeSMInt and typeShortInteger have the same four-character code, 'shor'.
Interacting With the User
When your application receives an Apple event, it may need to interact with the user. For example, it may need to display a dialog box asking the user for additional information or confirmation. You must use the AEInteractWithUser function to make sure your application is in the foreground before it actually interacts with the user.
Both the client application and the server application specify their preferences for user interaction. The AEInteractWithUser function checks the user interaction preferences set by each application. If both the client and the server allow user interaction, AEInteractWithUser usually posts a notification request, and the Notification Manager brings the server to the foreground after the user responds to the notification request.
The AEInteractWithUser function can also bring the server application directly to the foreground, but only if the client application is the active application on the same computer and has set two flags in the sendMode parameter of the AESend function: the kAEWaitReply flag, which indicates that it is waiting for a reply, and the kAECanSwitchLayer flag, which indicates that it wants the server application to come directly to the foreground rather than posting a notification request.
To specify its preferences for how the server application should interact with the user, the client application sets various flags in the sendMode parameter to AESend. The Apple Event Manager sets the corresponding flags in the keyInteractLevelAttr attribute of the Apple event.
The server application sets its preferences with the AESetInteractionAllowed function. This function lets your application specify whether it allows interaction with the user as a result of receiving an Apple event from itself; from itself and other processes on the local computer; or from itself, local processes, and processes from another computer on the network.
Your application calls the AEInteractWithUser function before interacting with the user. If AEInteractWithUser returns the noErr result code, then your application is currently in the front and free to interact with the user. If AEInteractWithUser returns the errAENoUserInteraction result code, the conditions didn’t allow user interaction and your application should not interact with the user.
The rest of this section explains how to set user interactions for the client and server applications and the practical effect these settings have when a server needs to interact with a user.
Setting the Client Application’s User Interaction Preferences
The client application sets its user interaction preferences by setting flags in the sendMode parameter to the AESend function. The Apple Event Manager automatically adds the specified flags to the keyInteractLevelAttr attribute of the Apple event. These flags are represented by the following constants:
Flag Description
kAENeverInteract The server application should never interact with the user in response to the Apple event. If this flag is set, AEInteractWithUser returns the errAENoUserInteraction result code. This flag is the default when an Apple event is sent to a remote application.
kAECanInteract The server application can interact with the user in response to the Apple event—by convention, if the user needs to supply information to the server. If this flag is set and the server allows interaction, AEInteractWithUser either brings the server application to the foreground or posts a notification request. This flag is the default when an Apple event is sent to a local application.
kAEAlwaysInteract The server application can interact with the user in response to the Apple event—by convention, whenever the server application normally asks a user to confirm a decision or interact in any other way, even if no additional information is needed from the user. If this flag is set and the server allows interaction, AEInteractWithUser either brings the server application to the foreground or posts a notification request.
For example, suppose a client application sends a Set Data event to a database application to change a customer’s address. The database application is configured to request user confirmation of changes to a customer’s record. In this case the client sets the kAECanInteract flag before sending the event. Thus, the database application attempts to interact with the user if interaction is allowed. If interaction is not allowed, the database makes the correction anyway without consulting the user. However, if the client application sends a Delete event to delete a customer’s record entirely and sets the kAEAlwaysInteract flag, the database application deletes the specified record only if it can interact with the user first and receives confirmation of the decision to delete a record. If interaction with the user is not allowed, the database application returns an error. By setting the kAEAlwaysInteract flag, the client application ensures that the entire record won’t be lost if the user sends the Delete event by mistake.
If the client application doesn’t specify any of the three user interaction flags, the Apple Event Manager sets either the kAENeverInteract or the kAECanInteract flag in the keyInteractLevelAttr attribute of the Apple event, depending on the location of the server application. If the server application is on a remote computer, the Apple Event Manager sets the kAENeverInteract flag as the default. If the server application is on the local computer, the Apple Event Manager sets the kAECanInteract flag as the default.
In addition to the three user interaction flags, the client application can set another flag in the sendMode parameter to AESend to request that the Apple Event Manager immediately bring the server application directly to the foreground instead of posting a notification request:
Flag Description
kAECanSwitchLayer If both the client and server allow interaction, and if the client application is the active application on the local computer and is waiting for a reply (that is, it has set the kAEWaitReply flag), AEInteractWithUser brings the server directly to the foreground. Otherwise, AEInteractWithUser uses the Notification Manager to request that the user bring the server application to the foreground.
Note that although the kAECanSwitchLayer flag must be set for the Apple Event Manager to bring the server application directly to the foreground, setting it does not guarantee that the Apple Event Manager will bypass the notification request if user interaction is permitted. Another flag, the kAEWaitReply flag, must also be set in the sendMode parameter, and the client application must provide an idle function.
The kAEWaitReply flag is one of three flags in the sendMode parameter that a client application can set to specify whether and how the client should wait for a reply. (For a description of these flags, see “Sending an Apple Event and Handling the Reply” on page 3-30.) If the client application is not waiting for a reply, the user may have continued with other work. An application switch at this point might be unexpected and would thus violate the principle of user control as described in Macintosh Human Interface Guidelines.
If the client application sets the kAEWaitReply flag, it should also provide an idle function when it calls AESend so that it can handle events such as update events that it receives while waiting for the reply. Idle functions are described in “Writing an Idle Function,” which begins on page 5-21.
When a server application calls AEInteractWithUser, the function first checks whether the kAENeverInteract flag in the keyInteractLevelAttr attribute of the Apple event is set. (The Apple Event Manager sets this attribute according to the flags specified in the sendMode parameter of AESend.) If the kAENeverInteract flag is set, AEInteractWithUser immediately returns the errAENoUserInteraction result code. If the client specified kAECanInteract or kAEAlwaysInteract, AEInteractWithUser checks the server’s preferences for user interaction.
Setting the Server Application’s User Interaction Preferences
The server sets its user interaction preferences by using the AESetInteractionAllowed function. This function specifies the conditions under which your application is willing to interact with the user.
myErr := AESetInteractionAllowed(level);
The level parameter is of type AEInteractAllowed.
TYPE AEInteractAllowed = (kAEInteractWithSelf,
kAEInteractWithLocal,
kAEInteractWithAll);
You can specify one of these values for the interaction level:
Flag Description
kAEInteractWithSelf Your server application can interact with the user in response to an Apple event only when your application is also the client application—that is, only when your application is sending the Apple event to itself.
kAEInteractWithLocal Your server application can interact with the user in response to an Apple event only if the client application is on the same computer as your application. This is the default if the server application does not call the function AESetInteractionAllowed.
kAEInteractWithAll Your server application can interact with the user in response to an Apple event sent by any client application on any computer.
If the server application does not set the user interaction level, AEInteractWithUser uses kAEInteractWithLocal as the value.
If the application sends itself an Apple event (that is, if the application is both the client and the server) without setting the kAENeverInteract flag, AEInteractWithUser always allows user interaction. If the client application is a process on the local computer and specifies kAECanInteract or kAEAlwaysInteract, and if the server has set the interaction level to kAEInteractWithLocal or kAEInteractWithAll, then AEInteractWithUser allows user interaction. If the client is a process on a remote computer on the network and specifies kAECanInteract or kAEAlwaysInteract, AEInteractWithUser allows user interaction only if the server specified the kAEInteractWithAll flag for the interaction level. In all other cases, AEInteractWithUser does not allow user interaction.
Requesting User Interaction
If your server application needs to interact with the user for any reason, it must call the AEInteractWithUser function to make sure it is in the foreground before it actually interacts with the user. When AEInteractWithUser allows user interaction (based on the client’s and server’s preferences), AEInteractWithUser brings the server application to the foreground—either directly or after the user responds to a notification request—and then returns a noErr result code. If AEInteractWithUser brings the server to the foreground directly, the client returns to the foreground immediately after the server has finished interacting with the user. If AEInteractWithUser brings the server to the foreground after the user responds to a notification request, the server remains in the foreground after completing the user interaction.
The AEInteractWithUser function specifies how long your handler is willing to wait for a response from the user. For example, if the timeout value is 900 ticks (15 seconds) and the Apple Event Manager posts a notification request, the Notification Manager begins to display a blinking icon in the upper-right corner of the screen, then removes the notification request (and the blinking icon) if the user does not respond within 15 seconds. (The discussion that follows describes some restrictions on the icons that can be displayed in this situation.)
Note that the timeout value passed to the AEInteractWithUser function is separate from the timeout value passed to the AESend function, which specifies how long the client application is willing to wait for the reply or return receipt from the server application. If AEInteractWithUser does not receive a response from the user within the specified time, AEInteractWithUser returns errAETimeout.
You may want to give the user a method of setting the interaction level. For example, some users may not want to be interrupted while background processing of an Apple event occurs, or they may not want to respond to dialog boxes when your application is handling Apple events sent from another computer.
Listing 4-14 illustrates the use of the AEInteractWithUser function. You call this function before your application displays a dialog box or otherwise interacts with the user when processing an Apple event. You specify a timeout value, a pointer to a Notification Manager record, and the address of an idle function as parameters to AEInteractWithUser.
Listing 4-14 Using the AEInteractWithUser function
{the attempt to interact failed; do any error handling}
DoError(myErr)
ELSE
{interact with the user by displaying a dialog box }
{ or by interacting in any other way that is necessary}
DisplayMyDialogBox;
You can set a timeout value, in ticks, in the first parameter to AEInteractWithUser. Use the kAEDefaultTimeout constant if you want the Apple Event Manager to use a default value for the timeout value. The Apple Event Manager uses a timeout value of about one minute if you specify this constant. You can also specify the kNoTimeOut constant if your application is willing to wait an indefinite amount of time for a response from the user. Usually you should provide a timeout value, so that your application can complete processing of the Apple event in a reasonable amount of time.
If you specify NIL instead of a Notification Manager record in the second parameter of AEInteractWithUser, the Apple Event Manager looks for an application icon with the ID specified by the application’s bundle ('BNDL') resource and the application’s file reference ('FREF') resource. The Apple Event Manager first looks for an 'SICN' resource with the specified ID; if it can’t find an 'SICN' resource, it looks for the 'ICN#' resource and compresses the icon to fit in the menu bar. The Apple Event Manager won’t look for any members of an icon family other than the icon specified in the 'ICN#' resource.
If the application doesn’t have 'SICN' or 'ICN#' resources, or if it doesn’t have a file reference resource, the Apple Event Manager passes NIL to the Notification Manager, and no icon appears in the upper-right corner of the screen. Therefore, if you want to display any icon other than those of type 'SICN' or 'ICN#', you must specify a notification record as the second parameter to the AEInteractWithUser function.
Note
If you want the Notification Manager to use a color icon when it posts a notification request, you should provide a Notification Manager record that specifies a 'cicn' resource.u
The AEInteractWithUser function posts a notification request only when user interaction is allowed and the kAECanSwitchLayer flag in the keyInteractLevelAttr attribute is not set.
The last parameter to AEInteractWithUser specifies an idle function provided by your application. Your idle function should handle any update events, null events, operating-system events, or activate events while your application is waiting to be brought to the front. See “Writing an Idle Function” on page 5-21 for more information.
Figure 4-1 illustrates a situation in which a client application (a forms application) might request a service from a server application (a database application). To perform this service, the server application must interact with the user.
Figure 4-1 A document with a button that triggers a Get Data event
Figure 4-1 shows part of an electronic form used to enter information about an order received by telephone. If the customer has ordered from the company before, the user can quickly retrieve the customer’s address and telephone number by clicking the Retrieve Customer Info button. In response, the forms application sends a Get Data event to a database application (SurfDB) currently open on the same computer. The Get Data event sent by the forms application (the client application for the ensuing transaction) asks SurfDB (the server) to locate the customer’s name in a table of addresses and return the customer’s address. When the forms application receives the reply Apple event, it can add the address data to the appropriate fields in the order form.
If SurfDB, as the server application, locates more than one entry for the specified customer name, it needs to interact with the user to determine which data to return in the reply Apple event. To interact with the user, the server application must be in the foreground, so that it can display a dialog box like the one shown in Figure 4-2.
Figure 4-2 A server application displaying a dialog box that requests information from the user
Figure 4-3, Figure 4-4, and Figure 4-5 illustrate two methods of dealing with this situation. Figure 4-3 shows the behavior of the server application that is common to both methods. In both cases, the server uses AESetInteractionAllowed to set its own interaction level to kAEInteractWithLocal. After calling AEResolve to locate the requested data, the server application discovers that two addresses match the name the user typed into the electronic form. The server then calls AEInteractWithUser with a timeout value of kAEDefaultTimeout so it can find out which address the user wants.
Figure 4-3 Handling user interaction
Figure 4-4 shows the circumstances in which the server application’s call to AEInteractWithUser shown in Figure 4-3 will cause the Apple Event Manager to bring the server application directly to the foreground. The client application sets the kAECanInteract, kAECanSwitchLayer, and kAEWaitReply flags in the sendMode parameter of the AESend function when it sends the Get Data event shown in the figure. These flags indicate that the client application expects the user to wait until the address appears in the appropriate fields of the electronic form before continuing with any other work. In this case, an automatic layer switch will not surprise the user and will avoid the additional user action required to respond to a notification request, so AEInteractWithUser brings the server application directly to the foreground and returns a noErr result code. The server application then displays the dialog box requesting that the user select the desired customer.
After the user selects the desired customer and clicks OK, the server application’s Get Data event handler returns. The Apple Event Manager immediately brings the client application to the foreground, and the client application displays the requested customer information in the appropriate fields.
Figure 4-4 Handling user interaction with the kAEWaitReply flag set
Figure 4-5 shows the circumstances in which the server application’s call to AEInteractWithUser in Figure 4-3 will cause the Apple Event Manager to post a notification request rather than bringing the server application directly to the foreground.
Figure 4-5 Handling user interaction with the kAEQueueReply flag set
The only difference between the Get Data event shown in Figure 4-4 and the Get Data event shown in Figure 4-5 is that the client application has set the kAEQueueReply flag instead of the kAEWaitReply flag in the sendMode parameter of AESend and has not set the kAECanSwitchLayer flag. This combination of flags indicates that the client application expects the user to continue filling in other parts of the form, such as the items being ordered; the address will just appear after a while, provided there is no duplicate name. In this case, an automatic layer switch would disrupt the user’s work. Instead of bringing the server application directly to the foreground, AEInteractWithUser uses the Notification Manager to post a notification request.
After the user has responded to the request and has brought the server application to the foreground, AEInteractWithUser returns a noErr result code, and the server application displays the dialog box requesting that the user select the desired customer. When the user selects a customer and clicks OK, the server application’s Get Data event handler returns. Because the user brought the server to the foreground manually, the server remains in the foreground after the handler returns.
Reference to Responding to Apple Events
This section describes the basic Apple Event Manager data structures and routines that your application can use to respond to Apple events. It also describes the syntax for application-defined Apple event handlers and coercion handlers that your application can provide for use by the Apple Event Manager.
For information about routines used to create and send Apple events, see the chapter “Creating and Sending Apple Events” in this book. For information about routines and data structures used with object specifier records, see the chapter “Resolving and Creating Object Specifier Records” in this book.
Data Structures Used by the Apple Event Manager
This section summarizes the major data structures used by the Apple Event Manager. For an overview of the relationships among these data structures, see “Data Structures Within Apple Events,” which begins on page 3-12.
Descriptor Records and Related Data Structures
Descriptor records are the fundamental data structures from which Apple events are constructed. A descriptor record is a data structure of type AEDesc.
TYPE AEDesc =
RECORD {descriptor record}
descriptorType: DescType; {type of data being passed}
dataHandle: Handle; {handle to data being passed}
END;
Field descriptions
descriptorType
A four-character string of type DescType that indicates the type of data being passed.
dataHandle A handle to the data being passed.
The descriptor type is a structure of type DescType, which in turn is of data type ResType—that is, a four-character code. Constants, rather than these four-character codes, are usually used to refer to descriptor types. Table 4-2 lists the constants for the basic descriptor types used by the Apple Event Manager.
Table 4-2 Descriptor types used by the Apple Event Manager (excluding those used with object specifier records)(continued)
Descriptor type Value Description
typeBoolean 'bool' Boolean value
typeChar 'TEXT' Unterminated string
typeLongInteger 'long' 32-bit integer
typeInteger 'long' 32-bit integer
typeShortInteger 'shor' 16-bit integer
typeSMInt 'shor' 16-bit integer
typeLongFloat 'doub' SANE double
typeFloat 'doub' SANE double
typeShortFloat 'sing' SANE single
typeSMFloat 'sing' SANE single
typeExtended 'exte' SANE extended
typeComp 'comp' SANE comp
typeMagnitude 'magn' Unsigned 32-bit integer
typeAEList 'list' List of descriptor records
typeAERecord 'reco' List of keyword-specified descriptor records
typeAppleEvent 'aevt' Apple event record
typeTrue 'true' TRUE Boolean value
continued
typeFalse 'fals' FALSE Boolean value
typeAlias 'alis' Alias record
typeEnumerated 'enum' Enumerated data
typeType 'type' Four-character code for event class or event ID
typeAppParameters 'appa' Process Manager launch parameters
typeProperty 'prop' Apple event property
typeFSS 'fss ' File system specification
typeKeyword 'keyw' Apple event keyword
typeSectionH 'sect' Handle to a section record
typeWildCard '****' Matches any type
typeApplSignature 'sign' Application signature
typeSessionID 'ssid' Session reference number
typeTargetID 'targ' Target ID record
typeProcessSerialNumber 'psn ' Process serial number
typeNull 'null' Nonexistent data (data handle is NIL)
For information about descriptor records and descriptor types used with object specifier records, see the chapter “Resolving and Creating Object Specifier Records” in this book.
Apple event attributes, Apple event parameters, object specifier records, tokens, and most of the other data structures used by the Apple Event Manager are constructed from one or more descriptor records. The Apple Event Manager identifies the various parts of an Apple event by means of keywords associated with the corresponding descriptor records. The AEKeyword data type is defined as a four-character code.
TYPE AEKeyword = PACKED ARRAY[1..4] OF Char;
Constants are typically used for keywords. A keyword combined with a descriptor record forms a keyword-specified descriptor record, which is defined by a data structure of type AEKeyDesc.
TYPE AEKeyDesc =
RECORD
descKey: AEKeyword; {keyword}
descContent: AEDesc; {descriptor record}
END;
Field descriptions
Field descriptions
descKey A four-character code of type AEKeyword that identifies the data in the descContent field.
descContent A descriptor record of type AEDesc.
Every Apple event includes an attribute that contains the address of the target application. A descriptor record that contains an application’s address is called an address descriptor record.
TYPE AEAddressDesc = AEDesc; {address descriptor record}
Many Apple Event Manager functions take or return lists of descriptor records in a special descriptor record called a descriptor list. A descriptor list is a structure of data type AEDescList whose data consists of a list of other descriptor records.
TYPE AEDescList = AEDesc; {list of descriptor records}
Other Apple Event Manager functions take or return lists of keyword-specified descriptor records in the form of an AE record. An AE record is a structure of data type AERecord whose data handle refers to a list of keyword-specified descriptor records.
TYPE AERecord = AEDescList; {list of keyword-specified }
{ descriptor records}
The handle for a descriptor list of data type AERecord refers to a list of keyword-specified descriptor records that specify Apple event parameters; they cannot specify Apple event attributes.
Finally, a full-fledged Apple event, including both attributes and parameters, is an Apple event record, which is a structure of data type AppleEvent.
TYPE AppleEvent = AERecord; {list of attributes and }
{ parameters for an Apple }
{ event}
The event class and event ID of an Apple event are specified in Apple Event Manager routines by structures of data types AEEventClass and AEEventID, respectively.
TYPE AEEventClass = PACKED ARRAY[1..4] OF Char;
TYPE AEEventID = PACKED ARRAY[1..4] OF Char;
For more information about descriptor records and the other data structures described in this section, see “Data Structures Within Apple Events,” which begins on page 3-12.
With the exception of array data records, which are described in the next section, the other Apple Event Manager data structures used in responding to Apple events are described in “Routines for Responding to Apple Events,” beginning on page 4-61, under the descriptions of the routines that use them.
Apple Event Array Data Types
The AEGetArray function (see page 4-77) creates a Pascal or C array that corresponds to an Apple event array in a descriptor list, and the AEPutArray function (see page 5-31) adds data specified in a buffer to a descriptor list as an Apple event array.
You can use the data type AEArrayType to define the type of Apple event array you want to add to or obtain from a descriptor list.
TYPE AEArrayType = (kAEDataArray, kAEPackedArray, kAEHandleArray,
kAEDescArray, kAEKeyDescArray);
When your application adds an Apple event array to a descriptor list, it provides the data for an Apple event array in an array data record, which is defined by the data type AEArrayData.
TYPE AEArrayData =
RECORD {data for an Apple event array}
CASE AEArrayType OF
kAEDataArray:
(AEDataArray: ARRAY[0..0] OF Integer);
kAEPackedArray:
(AEPackedArray: PACKED ARRAY[0..0] OF Char);
kAEHandleArray:
(AEHandleArray: ARRAY[0..0] OF Handle);
kAEDescArray:
(AEDescArray: ARRAY[0..0] OF AEDesc);
kAEKeyDescArray:
(AEKeyDescArray: ARRAY[0..0] OF AEKeyDesc);
END;
The type of array depends on the data for the array:
Array type Description of Apple event array
kAEDataArray Array items consist of data of the same size and same type, and are aligned on word boundaries.
kAEPackedArray Array items consist of data of the same size and same type, and are packed without regard for word boundaries.
kAEHandleArray Array items consist of handles to data of variable size and the same type.
kAEDescArray Array items consist of descriptor records of different descriptor types with data of variable size.
kAEKeyDescArray Array items consist of keyword-specified descriptor records with different keywords, different descriptor types, and data of variable size.
Array items in Apple event arrays of type kAEDataArray, kAEPackedArray, or kAEHandleArray must be factored—that is, contained in a factored descriptor list. Before adding array items to a factored descriptor list, you should provide both a pointer to the data that is common to all array items and the size of that common data when you first call AECreateList to create a factored descriptor list. When you call AEPutArray to add the array data to such a descriptor list, the Apple Event Manager automatically isolates the common data you specified in the call to AECreateList.
When you call AEGetArray or AEPutArray, you specify a pointer of data type AEArrayDataPointer that points to a buffer containing the data for the array.
TYPE AEArrayDataPointer = ^AEArrayData;
For more information about using AECreateList to create factored descriptor lists for arrays, see page 5-28. For information about using AEGetArray and AEPutArray, see page 4-77 and page 5-31, respectively.
Routines for Responding to Apple Events
This section describes the Apple Event Manager routines you can use to create and manage the Apple event dispatch tables, dispatch Apple events, extract information from Apple events, request user interaction, request more time to respond to Apple events, suspend and resume Apple event handling, delete descriptor records, deallocate memory for descriptor records, create and manage the coercion handler and special handler dispatch tables, and get information about the Apple Event Manager.
Because the Apple Event Manager uses the services of the Event Manager, which in turn uses the services of the PPC Toolbox, the routines described in this section may return Event Manager and PPC Toolbox result codes in addition to the Apple Event Manager result codes listed.
Creating and Managing the Apple Event Dispatch Tables
An Apple event dispatch table contains entries that specify the event class and event ID that refer to one or more Apple events, the address of the handler routine that handles those Apple events, and a reference constant. You can use the AEInstallEventHandler function to add entries to the Apple event dispatch table. This function sets up the initial mapping between the handlers in your application and the Apple events that they handle.
To get the address of a handler currently in the Apple event dispatch table, use the AEGetEventHandler function. If you need to remove any of your Apple event handlers after the mapping between handlers and Apple events is established, you can use the AERemoveEventHandler function.
AEInstallEventHandler
You can use the AEInstallEventHandler function to add an entry to either your application’s Apple event dispatch table or the system Apple event dispatch table.
FUNCTION AEInstallEventHandler (theAEEventClass: AEEventClass;
theAEEventID: AEEventID;
handler: EventHandlerProcPtr;
handlerRefcon: LongInt;
isSysHandler: Boolean): OSErr;
theAEEventClass
The event class for the Apple event or events to be dispatched for this entry. The AEEventClass data type is defined as a four-character code:
TYPE AEEventClass = PACKED ARRAY[1..4] OF Char;
theAEEventID
The event ID for the Apple event or events to be dispatched for this entry. The AEEventID data type is defined as a four-character code:
TYPE AEEventID = PACKED ARRAY[1..4] OF Char;
handler A pointer to an Apple event handler for this dispatch table entry. Note that a handler in the system dispatch table must reside in the system heap; this means that if the value of the isSysHandler parameter is TRUE, the handler parameter should point to a location in the system heap. Otherwise, if you put your system handler code in your application heap, you must use AERemoveEventHandler to remove the handler before your application terminates.
handlerRefcon
A reference constant that is passed by the Apple Event Manager to the handler each time the handler is called. If your handler doesn’t use a reference constant, use 0 as the value of this parameter.
isSysHandler
Specifies the dispatch table to which you want to add the handler. If the value of isSysHandler is TRUE, the Apple Event Manager adds the handler to the system Apple event dispatch table. Entries in the system dispatch table are available to all applications. If the value of isSysHandler is FALSE, the Apple Event Manager adds the handler to your application’s Apple event dispatch table. The application’s dispatch table is searched first; the system dispatch table is searched only if the necessary handler is not found in your application’s dispatch table.
DESCRIPTION
The AEInstallEventHandler function creates an entry in the Apple event dispatch table. You must supply parameters that specify the event class, the event ID, the address of the handler that handles Apple events of the specified event class and event ID, and whether the handler is to be added to the system Apple event dispatch table or your application’s Apple event dispatch table. You can also specify a reference constant that the Apple Event Manager passes to your handler whenever your handler processes an Apple event.
The parameters theAEEventClass and theAEEventID specify the event class and event ID of the Apple events to be handled by the handler for this dispatch table entry. For these parameters, you must provide one of the following combinations:
n the event class and event ID of a single Apple event to be dispatched to the handler
n the typeWildCard constant for theAEEventClass and an event ID for theAEEventID, which indicate that Apple events from all event classes whose event IDs match theAEEventID should be dispatched to the handler
n an event class for theAEEventClass and the typeWildCard constant for theAEEventID, which indicate that all events from the specified event class should be dispatched to the handler
n the typeWildCard constant for both the theAEEventClass and theAEEventID parameters, which indicates that all Apple events should be dispatched to the handler
IMPORTANT
If you use the typeWildCard constant for either the theAEEventClass or the theAEEventID parameter (or for both parameters), the corresponding handler must return the error errAEEventNotHandled if it does not handle a particular event.s
If there was already an entry in the specified dispatch table for the same event class and event ID, it is replaced. Therefore, before installing a handler for a particular Apple event in the system dispatch table, use the AEGetEventHandler function (described next) to determine whether the table already contains a handler for that event. If an entry exists, AEGetEventHandler returns a reference constant and a pointer to that event handler. Chain the existing handler to your handler by providing pointers to the previous handler and its reference constant in the handlerRefcon parameter of AEInstallEventHandler. When your handler is done, use these pointers to call the previous handler. If you remove your system Apple event handler, be sure to reinstall the chained handler.
SPECIAL CONSIDERATIONS
Before an application calls a system Apple event handler, system software has set up the A5 register for the calling application. For this reason, if you provide a system Apple event handler, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system handler may crash.
RESULT CODESnoErr 0 No error
paramErr –50 Parameter error (handler pointer is NIL or odd)
memFullErr –108 Not enough room in heap zone
SEE ALSO
For more information about installing Apple event handlers, see “Installing Entries in the Apple Event Dispatch Tables,” which begins on page 4-7.
AEGetEventHandler
You can use the AEGetEventHandler function to get an entry from an Apple event dispatch table.
FUNCTION AEGetEventHandler (theAEEventClass: AEEventClass;
theAEEventID: AEEventID;
VAR handler: EventHandlerProcPtr;
VAR handlerRefcon: LongInt;
isSysHandler: Boolean): OSErr;
theAEEventClass
The value of the event class field of the dispatch table entry for the desired handler.
theAEEventID
The value of the event ID field of the dispatch table entry for the desired handler.
handler The AEGetEventHandler function returns, in this parameter, a pointer to the specified handler.
handlerRefcon
The AEGetEventHandler function returns, in this parameter, the reference constant from the dispatch table entry for the specified handler.
isSysHandler
Specifies the Apple event dispatch table from which to get the handler. If the value of isSysHandler is TRUE, the AEGetEventHandler function returns the handler from the system dispatch table. If the value is FALSE, AEGetEventHandler returns the handler from your application’s dispatch table.
DESCRIPTION
The AEGetEventHandler function returns, in the handler parameter, a pointer to the handler for the Apple event dispatch table entry you specify in the parameters theAEEventClass and theAEEventID. You can use the typeWildCard constant for either or both of these parameters; however, AEGetEventHandler returns an error unless an entry exists that specifies typeWildCard in exactly the same way. For example, if you specify typeWildCard in both the theAEEventClass parameter and the theAEEventID parameter, the Apple Event Manager will not return the first handler for any event class and event ID in the dispatch table; instead, the dispatch table must contain an entry that specifies type typeWildCard for both the event class and the event ID.
RESULT CODESnoErr 0 No error
errAEHandlerNotFound –1717 No handler found for an Apple event
SEE ALSO
For an explanation of wildcard values, see the description of the AEInstallEventHandler function on page 4-62.
AERemoveEventHandler
You can use the AERemoveEventHandler function to remove an entry from an Apple event dispatch table.
FUNCTION AERemoveEventHandler (theAEEventClass: AEEventClass;
theAEEventID: AEEventID;
handler: EventHandlerProcPtr;
isSysHandler: Boolean): OSErr;
theAEEventClass
The event class for the handler whose entry you want to remove from the dispatch table.
theAEEventID
The event ID for the handler whose entry you want to remove from the Apple event dispatch table.
handler A pointer to the handler to be removed. Although the parameters theAEEventClass and theAEEventID would be sufficient to identify the handler to be removed, providing the handler parameter is a recommended safeguard that ensures that you remove the correct handler. If the value of this parameter is NIL, the Apple Event Manager relies solely on the event class and event ID to identify the handler to be removed.
isSysHandler
Specifies the dispatch table from which to remove the handler. If the value of isSysHandler is TRUE, AERemoveEventHandler removes the handler from the system dispatch table. If the value is FALSE, AERemoveEventHandler removes the handler from your application’s dispatch table.
DESCRIPTION
The AERemoveEventHandler function removes the Apple event dispatch table entry you specify in the parameters theAEEventClass, theAEEventID, and handler. You can use the typeWildCard constant for the theAEEventClass or the theAEEventID parameter, or for both parameters; however, AERemoveEventHandler returns an error unless an entry exists that specifies typeWildCard in exactly the same way. For example, if you specify typeWildCard in both the theAEEventClass parameter and the theAEEventID parameter, the Apple Event Manager will not remove the first handler for any event class and event ID in the dispatch table; instead, the dispatch table must contain an entry that specifies type typeWildCard for both the event class and the event ID.
RESULT CODESnoErr 0 No error
errAEHandlerNotFound –1717 No handler found for an Apple event
SEE ALSO
For an explanation of wildcard values, see the description of the AEInstallEventHandler function on page 4-62.
Dispatching Apple Events
After receiving a high-level event (and optionally determining whether it is a type of high-level event other than an Apple event that your application might support), your application typically calls the AEProcessAppleEvent function to determine the type of Apple event received and call the corresponding handler.
AEProcessAppleEvent
You can use the AEProcessAppleEvent function to call the appropriate handler for a specified Apple event.
FUNCTION AEProcessAppleEvent
(theEventRecord: EventRecord): OSErr;
theEventRecord
The event record for the Apple event.
DESCRIPTION
The AEProcessAppleEvent function looks first in the application’s special handler dispatch table for an entry that was installed with the constant keyPreDispatch. If the application’s special handler dispatch table does not include such a handler or if the handler returns errAEEventNotHandled, the function looks in the application’s Apple event dispatch table for an entry that matches the event class and event ID of the specified Apple event.
If the application’s Apple event dispatch table does not include such a handler or if the handler returns errAEEventNotHandled, the AEProcessAppleEvent function looks in the system special handler dispatch table for an entry that was installed with the constant keyPreDispatch. If the system special handler dispatch table does not include such a handler or if the handler returns errAEEventNotHandled, the function looks in the system Apple event dispatch table for an entry that matches the event class and event ID of the specified Apple event.
If the system Apple event dispatch table does not include such a handler, the Apple Event Manager returns the result code errAEEventNotHandled to the server application and, if the client application is waiting for a reply, to the client application.
If AEProcessAppleEvent finds an entry in one of the dispatch tables that matches the event class and event ID of the specified Apple event, it calls the corresponding handler.
SPECIAL CONSIDERATIONS
If an Apple event dispatch table contains one entry for an event class and a specific event ID, and also contains another entry that is identical except that it specifies a wildcard value for either the event class or the event ID, the Apple Event Manager dispatches the more specific entry. For example, if an Apple event dispatch table includes one entry that specifies the event class as kAECoreSuite and the event ID as kAEDelete, and another entry that specifies the event class as kAECoreSuite and the event ID as typeWildCard, the Apple Event Manager dispatches the Apple event handler associated with the entry that specifies the event ID as kAEDelete.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
bufferIsSmall –607 Buffer is too small
noOutstandingHLE –608 No outstanding high-level event
errAECorruptData –1702 Data in an Apple event could not be read
errAENewerVersion –1706 Need a newer version of the Apple Event Manager
errAEEventNotHandled –1708 Event wasn’t handled by an Apple event handler
SEE ALSO
For an example of the use of AEProcessAppleEvent, see Listing 4-2 on page 4-6.
For a description of an Apple event handler, see page 4-105.
For more information about event processing, see the chapter “Event Manager” in Inside Macintosh: Macintosh Toolbox Essentials.
Getting Data or Descriptor Records Out of Apple Event Parameters and Attributes
The Apple Event Manager provides four functions that allow you to get data from Apple event parameters and attributes. The AEGetParamPtr and AEGetParamDesc functions get data from a specified Apple event parameter. The AEGetAttributePtr and AEGetAttributeDesc functions get data from a specified Apple event attribute.
AEGetParamPtr
You can use the AEGetParamPtr function to get a pointer to a buffer that contains the data from a specified Apple event parameter.
FUNCTION AEGetParamPtr (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
desiredType: DescType;
VAR typeCode: DescType; dataPtr: Ptr;
maximumSize: Size;
VAR actualSize: Size): OSErr;
theAppleEvent
The Apple event containing the desired parameter.
theAEKeyword
The keyword that specifies the desired parameter.
desiredType
The desired descriptor type for the data to be returned; if the requested Apple event parameter is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType
is typeWildCard, no coercion is performed, and the descriptor type of the returned data is the same as the descriptor type of the Apple event parameter.
typeCode The descriptor type of the returned data.
dataPtr A pointer to the buffer in which the returned data is stored.
maximumSize
The maximum length, in bytes, of the data to be returned. You must allocate at least this amount of storage for the buffer specified by the dataPtr parameter.
actualSize
The length, in bytes, of the data for the specified Apple event parameter. If this value is larger than the value of the maximumSize parameter, not all of the data for the parameter was returned.
DESCRIPTION
The AEGetParamPtr function uses a buffer to return the data from a specified Apple event parameter, which it attempts to coerce to the descriptor type specified by the desiredType parameter.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
SEE ALSO
For examples of the use of AEGetParamPtr, see “Getting Data Out of an Apple Event,” which begins on page 4-25.
AEGetParamDesc
You can use the AEGetParamDesc function to get the descriptor record for a specified Apple event parameter.
FUNCTION AEGetParamDesc (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
desiredType: DescType;
VAR result: AEDesc): OSErr;
theAppleEvent
The Apple event containing the desired parameter.
theAEKeyword
The keyword that specifies the desired parameter.
desiredType
The desired descriptor type for the descriptor record to be returned; if the requested Apple event parameter is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the returned data is the same as the descriptor type of the Apple event parameter.
result The descriptor record from the desired Apple event parameter coerced to the descriptor type specified in desiredType.
DESCRIPTION
The AEGetParamDesc function returns, in the result parameter, the descriptor record for a specified Apple event parameter, which it attempts to coerce to the descriptor type specified by the desiredType parameter. Your application should call the AEDisposeDesc function to dispose of the resulting descriptor record after your application has finished using it.
If AEGetParamDesc returns a nonzero result code, it returns a null descriptor record unless the Apple Event Manager is not available because of limited memory.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
SEE ALSO
For an example of the use of AEGetParamDesc, see “Getting Data Out of an Apple Event Parameter,” which begins on page 4-26.
AEGetAttributePtr
You can use the AEGetAttributePtr function to get a pointer to a buffer that contains the data from a specified Apple event attribute.
FUNCTION AEGetAttributePtr (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
desiredType: DescType;
VAR typeCode: DescType; dataPtr: Ptr;
maximumSize: Size;
VAR actualSize: Size): OSErr;
theAppleEvent
The Apple event containing the desired attribute.
theAEKeyword
The keyword that specifies the desired attribute.
TYPE AEKeyword = PACKED ARRAY[1..4] OF Char;
The keyword can be any of the constants listed in the description that follows.
desiredType
The desired descriptor type for the data to be returned; if the requested Apple event attribute is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the returned data is the same as the descriptor type of the Apple event attribute.
typeCode The descriptor type of the returned data.
dataPtr A pointer to the buffer in which the returned data is stored.
maximumSize
The maximum length, in bytes, of the data to be returned. You must allocate at least this amount of storage for the buffer specified by the dataPtr parameter.
actualSize
The length, in bytes, of the data for the specified Apple event attribute. If this value is larger than the value of the maximumSize parameter, not all of the data for the attribute was returned.
DESCRIPTION
The AEGetAttributePtr function uses a buffer to return the data from an Apple event attribute with the specified keyword, which it attempts to coerce to the descriptor type specified by the desiredType parameter. You can specify the parameter theAEKeyWord using any of these constants:
CONST
keyAddressAttr = 'addr'; {address of target or }
{ client application}
keyEventClassAttr = 'evcl'; {event class}
keyEventIDAttr = 'evid'; {event ID}
keyEventSourceAttr = 'esrc'; {nature of source }
{ application}
keyInteractLevelAttr = 'inte'; {settings to allow the }
keyOptionalKeywordAttr = 'optk'; {list of optional }
{ parameters for Apple }
{ event}
keyOriginalAddressAttr = 'from'; {address of original source }
{ of Apple event; available }
{ beginning with version }
{ 1.01 of Apple Event }
{ Manager}
keyReturnIDAttr = 'rtid'; {return ID for reply Apple }
{ event}
keyTimeoutAttr = 'timo'; {length of time in ticks }
{ that client will wait }
{ for reply or result from }
{ the server}
keyTransactionIDAttr = 'tran'; {transaction ID identifying }
{ a series of Apple events}
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
SEE ALSO
For an example of the use of the AEGetAttributePtr function, see “Getting Data Out of an Attribute” and “Writing Apple Event Handlers,” which begin on page 4-28 and page 4-33, respectively.
AEGetAttributeDesc
You can use the AEGetAttributeDesc function to get the descriptor record for a specified Apple event attribute.
FUNCTION AEGetAttributeDesc (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
desiredType: DescType;
VAR result: AEDesc): OSErr;
theAppleEvent
The Apple event containing the desired attribute.
theAEKeyword
The keyword that specifies the desired attribute.
TYPE AEKeyword = PACKED ARRAY[1..4] OF Char;
The keyword can be any of the constants listed in the description of AEGetAttributePtr on page 4-71.
desiredType
The desired descriptor type for the descriptor record to be returned; if the requested Apple event attribute is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the returned data is the same as the descriptor type of the Apple event attribute.
result A copy of the descriptor record from the desired attribute coerced to the descriptor type specified by the desiredType parameter.
DESCRIPTION
The AEGetAttributeDesc function returns, in the result parameter, the descriptor record for the Apple event attribute with the specified keyword. Your application should call the AEDisposeDesc function to dispose of the resulting descriptor record after your application has finished using it.
If AEGetAttributeDesc returns a nonzero result code, it returns a null descriptor record unless the Apple Event Manager is not available because of limited memory.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
Counting the Items in Descriptor Lists
The AECountItems function counts the number of descriptor records in any descriptor list, including an Apple event record.
AECountItems
You can use the AECountItems function to count the number of descriptor records in any descriptor list.
FUNCTION AECountItems (theAEDescList: AEDescList;
VAR theCount: LongInt): OSErr;
theAEDescList
The descriptor list to be counted.
theCount The AECountItems function returns the number of descriptor records in the specified descriptor list in this parameter.
RESULT CODESnoErr 0 No error
errAENotAEDesc –1704 Not a valid descriptor record
SEE ALSO
For an example of the use of AECountItems, see “Getting Data Out of a Descriptor List,” which begins on page 4-31.
Getting Items From Descriptor Lists
The Apple Event Manager provides three functions that allow you to get items from any descriptor list, including an Apple event record. The AEGetNthPtr and AEGetNthDesc functions give you access to the data in a descriptor list. The AEGetArray function gets data from an array contained in a descriptor list.
AEGetNthPtr
You can use the AEGetNthPtr function to get a pointer to a buffer that contains a copy of a descriptor record from any descriptor list.
FUNCTION AEGetNthPtr (theAEDescList: AEDescList; index: LongInt;
desiredType: DescType;
VAR theAEKeyword: AEKeyword;
VAR typeCode: DescType; dataPtr: Ptr;
maximumSize: Size;
VAR actualSize: Size): OSErr;
theAEDescList
The descriptor list containing the desired descriptor record.
index The position of the desired descriptor record in the list (for example, 2 specifies the second descriptor record).
desiredType
The desired descriptor type for the copy of the descriptor record to be returned; if the desired descriptor record is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the copied descriptor record is the same as the descriptor type of the original descriptor record.
theAEKeyword
The keyword of the specified descriptor record, if you are getting data from a list of keyword-specified descriptor records; otherwise, AEGetNthPtr returns the value typeWildCard.
typeCode The descriptor type of the returned descriptor record.
dataPtr A pointer to the buffer in which the returned descriptor record is stored.
maximumSize
The maximum length, in bytes, of the data to be returned. You must allocate at least this amount of storage for the buffer specified by the dataPtr parameter.
actualSize
The length, in bytes, of the data for the specified descriptor record. If this value is larger than the value of the maximumSize parameter, not all of the data for the descriptor record was returned.
DESCRIPTION
The AEGetNthPtr function uses a buffer to return a specified descriptor record from a specified descriptor list; the function attempts to coerce the descriptor record to the descriptor type specified by the desiredType parameter.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
SEE ALSO
For an example of the use of AEGetNthPtr, see Listing 4-10 on page 4-33.
AEGetNthDesc
You can use the AEGetNthDesc function to get a copy of a descriptor record from any descriptor list.
FUNCTION AEGetNthDesc (theAEDescList: AEDescList; index: LongInt;
desiredType: DescType;
VAR theAEKeyword: AEKeyword;
VAR result: AEDesc): OSErr;
theAEDescList
The descriptor list containing the desired descriptor record.
index The position of the desired descriptor record in the list (for example, 2 specifies the second descriptor record).
desiredType
The desired descriptor type for the copy of the descriptor record to be returned; if the desired descriptor record is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the copied descriptor record is the same as the descriptor type of the original descriptor record.
theAEKeyword
The keyword of the specified descriptor record, if you are getting data from a list of keyword-specified descriptor records; otherwise, AEGetNthDesc returns the value typeWildCard.
result A copy of the desired descriptor record coerced to the descriptor type specified by the desiredType parameter.
DESCRIPTION
The AEGetNthDesc function returns a specified descriptor record from a specified descriptor list.Your application should call the AEDisposeDesc function to dispose of the resulting descriptor record after your application has finished using it.
If AEGetNthDesc returns a nonzero result code, it returns a descriptor record of descriptor type typeNull. A descriptor record of this type does not contain any data.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
AEGetArray
You can use the AEGetArray function to convert an Apple event array (an array created with the AEPutArray function and stored in a descriptor list) to the corresponding Pascal or C array and place the converted array in a buffer for which you have provided a pointer.
FUNCTION AEGetArray (theAEDescList: AEDescList;
arrayType: AEArrayType;
arrayPtr: AEArrayDataPointer;
maximumSize: Size;
VAR itemType: DescType; VAR itemSize: Size;
VAR itemCount: LongInt): OSErr;
theAEDescList
A descriptor list containing the desired array. If the array is of type kAEDataArray, kAEPackedArray, or kAEHandleArray, the descriptor list must be factored.
arrayType The Apple event array type to be converted. This is specified by one of the following constants: kAEDataArray, kAEPackedArray, kAEHandleArray, kAEDescArray, or kAEKeyDescArray.
arrayPtr A pointer to the buffer for storing the array.
maximumSize
The maximum length, in bytes, of the buffer for storing the array.
itemType For arrays of type kAEDataArray, kAEPackedArray, or kAEHandleArray, the AEGetArray function returns the descriptor type of the returned array items in this parameter.
itemSize For arrays of type kAEDataArray or kAEPackedArray, the AEGetArray function returns the size (in bytes) of the returned array items in this parameter.
itemCount The AEGetArray function returns the number of items in the resulting array in this parameter.
DESCRIPTION
The AEGetArray function uses a buffer identified by the pointer in the arrayPtr parameter to return the converted data for the Apple event array specified by the theAEDescList parameter. Even if the descriptor list that contains the array is factored, the converted data for each array item includes the data common to all the descriptor records in the list. The Apple Event Manager automatically reconstructs the common data for each item when you call AEGetArray.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
SEE ALSO
For more information about data types and constants used with AEGetArray, see “Apple Event Array Data Types” on page 4-60.
For information about creating and factoring descriptor lists for Apple event arrays, see the description of AECreateList on page 5-28. For information about adding an Apple event array to a descriptor list, see the description of AEPutArray on page 5-31.
Getting Data and Keyword-Specified Descriptor Records Out of AE Records
The Apple Event Manager provides two functions, AEGetKeyPtr and AEGetKeyDesc, that allow you to get data and descriptor records out of an AE record or an Apple event record.
AEGetKeyPtr
You can use the AEGetKeyPtr function to get a pointer to a buffer that contains the data from a keyword-specified descriptor record. You can use this function to get data from an AE record or an Apple event record.
FUNCTION AEGetKeyPtr (theAERecord: AERecord;
theAEKeyword: AEKeyword;
desiredType: DescType;
VAR typeCode: DescType;
dataPtr: Ptr; maximumSize: Size;
VAR actualSize: Size): OSErr;
theAERecord
The AE record containing the desired data.
theAEKeyword
The keyword that specifies the desired descriptor record.
desiredType
The desired descriptor type for the data to be returned; if the requested data is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of returned data is the same as the descriptor type of the original data.
typeCode The descriptor type of the returned data.
dataPtr A pointer to the buffer for storing the data.
maximumSize
The maximum length, in bytes, of the data to be returned. You must allocate at least this amount of storage for the buffer specified by the dataPtr parameter.
actualSize
The length, in bytes, of the data for the keyword-specified descriptor record. If this value is larger than the value of the maximumSize parameter, not all of the data for the parameter was returned.
DESCRIPTION
The AEGetKeyPtr function uses a buffer to return the data from a keyword-specified Apple event parameter, which the function attempts to coerce to the descriptor type specified by the desiredType parameter.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
AEGetKeyDesc
You can use the AEGetKeyDesc function to get the descriptor record for a keyword-specified descriptor record. You can use this function to get a descriptor record out of an AE record or an Apple event record.
FUNCTION AEGetKeyDesc (theAERecord: AERecord;
theAEKeyword: AEKeyword;
desiredType: DescType;
VAR result: AEDesc): OSErr;
theAERecord
The AE record containing the desired descriptor record.
theAEKeyword
The keyword that specifies the desired descriptor record.
desiredType
The desired descriptor type for the descriptor record to be returned; if the requested descriptor record is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the returned descriptor record is the same as the descriptor type of the original descriptor record.
result A copy of the keyword-specified descriptor record, coerced to the descriptor type specified in the desiredType parameter.
DESCRIPTION
The AEGetKeyDesc function returns a copy of the descriptor record for a keyword-specified descriptor record. Your application should call the AEDisposeDesc function to dispose of the resulting descriptor record after your application has finished using it.
If AEGetKeyDesc returns a nonzero result code, it returns a descriptor record of descriptor type typeNull. A descriptor record of this type does not contain any data.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
Requesting User Interaction
The Apple Event Manager provides three functions that allow you to set or request user interaction levels and to initiate user interaction when your application is the server application. The AESetInteractionAllowed and AEGetInteractionAllowed functions specify and return, respectively, the current user interaction preferences. Your application should call the AEInteractWithUser function before actually interacting with the user in response to an Apple event.
AESetInteractionAllowed
You can use the AESetInteractionAllowed function to specify your application’s user interaction preferences for responding to an Apple event.
FUNCTION AESetInteractionAllowed
(level: AEInteractAllowed): OSErr;
level The user interaction level to be set.
DESCRIPTION
The AESetInteractionAllowed function sets the user interaction level for a server application’s response to an Apple event. The level parameter must be one of three flags: kAEInteractWithSelf, kAEInteractWithLocal, or kAEInteractWithAll.
Specifying the kAEInteractWithSelf flag allows the server application to interact with the user in response to an Apple event only when the client application and server application are the same—that is, only when the application is sending the Apple event to itself.
Specifying the kAEInteractWithLocal flag allows the server application to interact with the user in response to an Apple event only if the client application is on the same computer as the server application; this is the default if the AESetInteractionAllowed function is not used.
Specifying the kAEInteractWithAll flag allows the server application to interact with the user in response to an Apple event sent from any client application on any computer.
RESULT CODEnoErr 0 No error
SEE ALSO
For more information about setting user preferences for a server application, see “Setting the Server Application’s User Interaction Preferences” on page 4-48.
AEGetInteractionAllowed
You can use the AEGetInteractionAllowed function to get the current user interaction preferences for responding to an Apple event.
FUNCTION AEGetInteractionAllowed
(VAR level: AEInteractAllowed): OSErr;
level The current user interaction level, using the data type AEInteractAllowed.
TYPE AEInteractAllowed = (kAEInteractWithSelf,
kAEInteractWithLocal,
kAEInteractWithAll);
DESCRIPTION
The AEGetInteractionAllowed function returns, in the level parameter, a value that indicates the user interaction preferences for responding to an Apple event. The value, set by a previous call to AESetInteractionAllowed, is one of the following flags: kAEInteractWithSelf, kAEInteractWithLocal, or kAEInteractWithAll. The default value of kAEInteractWithLocal is returned if your application has not used AESetInteractionAllowed to set the interaction level explicitly.
The kAEInteractWithSelf flag indicates that the server application may interact with the user in response to an Apple event only when the client application and server application are the same—that is, only when the application is sending the Apple event to itself.
The kAEInteractWithLocal flag indicates that the server application may interact with the user in response to an Apple event only if the client application is on the same computer as the server application. This is the default if your application has not used the AESetInteractionAllowed function to set the interaction level explicitly.
The kAEInteractWithAll flag indicates that the server application may interact with the user in response to an Apple event sent from any client application on any computer.
RESULT CODEnoErr 0 No error
AEInteractWithUser
You can use the AEInteractWithUser function to initiate interaction with the user when your application is a server application responding to an Apple event.
FUNCTION AEInteractWithUser (timeOutInTicks: LongInt;
nmReqPtr: NMRecPtr;
idleProc: IdleProcPtr): OSErr;
timeOutInTicks
The amount of time (in ticks) that your handler is willing to wait for a response from the user. You can specify a number of ticks or use one of the following constants:
CONST kAEDefaultTimeout = -1; {value determined }
{ by AEM}
kNoTimeOut = -2; {wait until reply }
{ comes back}
nmReqPtr A pointer to a Notification Manager record provided by your application. You can specify NIL for this parameter to get the default notification handling provided by the Apple Event Manager.
idleProc A pointer to your application’s idle function, which handles events while waiting for the Apple Event Manager to return control.
DESCRIPTION
Your application should call the AEInteractWithUser function before displaying a dialog box or alert box or otherwise interacting with the user in response to an Apple event. If the user interaction preference settings permit the application to come to the foreground, this function brings your application to the front, either directly or by posting a notification request.
Your application should normally pass a notification record in the nmReqPtr parameter rather than specifying NIL for default notification handling. If you specify NIL, the Apple Event Manager looks for an application icon with the ID specified by the application’s bundle ('BNDL') resource and the application’s file reference ('FREF') resource. The Apple Event Manager first looks for an 'SICN' resource with the specified ID; if it can’t find an 'SICN' resource, it looks for the 'ICN#' resource and compresses the icon to fit in the menu bar. The Apple Event Manager won’t look for any members of an icon family other than the icon specified in the 'ICN#' resource.
If the application doesn’t have 'SICN' or 'ICN#' resources, or if it doesn’t have a file reference resource, the Apple Event Manager passes NIL to the Notification Manager, and no icon appears in the upper-right corner of the screen. Therefore, if you want to display any icon other than those of type 'SICN' or 'ICN#', you must specify a notification record as the second parameter to the AEInteractWithUser function.
Note
Note
If you want the Notification Manager to use a color icon when it posts a notification request, you should provide a Notification Manager record that specifies a 'cicn' resource.u
The AEInteractWithUser function checks whether the client application set the kAENeverInteract flag for the Apple event and, if so, returns an error. If not, then the AEInteractWithUser function checks the server application’s preference set by the AESetInteractionAllowed function and compares it against the source of the Apple event—that is, whether it came from the same application, another process on the same computer, or a process running on another computer. The AEInteractWithUser function returns the errAENoUserInteraction result code if the user interaction preferences don’t allow user interaction. If user interaction is allowed, the Apple Event Manager brings your application to the front, either directly or by posting a notification request. If AEInteractWithUser returns the noErr result code, then your application is in the foreground and is free to interact with the user.
RESULT CODESnoErr 0 No error
errAETimeout –1712 Apple event timed out
errAENoUserInteraction –1713 No user interaction allowed
SEE ALSO
For information about idle functions, see “Writing an Idle Function” on page 5-21.
For examples of the use of the AEInteractWithUser function, see “Interacting With the User,” which begins on page 4-45.
Requesting More Time to Respond to Apple Events
The AEResetTimer function resets the timeout value for an Apple event to its starting value. A server application can call this function when it knows it cannot fulfill a client application’s request (either by returning a result or by sending back a reply Apple event) before the client application is due to time out.
AEResetTimer
You can use the AEResetTimer function to reset the timeout value for an Apple event to its starting value.
FUNCTION AEResetTimer (reply: AppleEvent): OSErr;
reply The default reply for an Apple event, provided by the Apple Event Manager.
DESCRIPTION
When your application calls AEResetTimer, the Apple Event Manager for the server application uses the default reply to send a Reset Timer event to the client application; the Apple Event Manager for the client application’s computer intercepts this Apple event and resets the client application’s timer for the Apple event. (The Reset Timer event is never dispatched to a handler, so the client application does not need a handler for it.)
RESULT CODEnoErr 0 No error
errAEReplyNotValid –1709 AEResetTimer was passed an invalid reply
Suspending and Resuming Apple Event Handling
When your application calls AEProcessAppleEvent and one of your event handlers is invoked, the Apple Event Manager normally assumes that your application has finished handling the event when the event handler returns. At this point, the Apple Event Manager disposes of the event. However, some applications, such as multi-session servers or any applications that implement their own internal event queueing, may need to defer handling of the event.
The AESuspendTheCurrentEvent, AEResumeTheCurrentEvent, AESetTheCurrentEvent, and AEGetTheCurrentEvent functions described in this section allow you to suspend and resume Apple event handling, specify the Apple event to be handled, and identify an Apple event that is currently being handled.
AESuspendTheCurrentEvent
You can use the AESuspendTheCurrentEvent function to suspend the processing of the Apple event that is currently being handled.
FUNCTION AESuspendTheCurrentEvent
(theAppleEvent: AppleEvent): OSErr;
theAppleEvent
The Apple event whose handling is to be suspended. Although the Apple Event Manager doesn’t need this parameter to identify the Apple event currently being handled, providing it is a safeguard that you are suspending the correct Apple event.
DESCRIPTION
After a server application makes a successful call to the AESuspendTheCurrentEvent function, it is no longer required to return a result or a reply for the Apple event that was being handled. It can, however, return a result if it later calls the AEResumeTheCurrentEvent function to resume event processing.
The Apple Event Manager does not automatically dispose of Apple events that have been suspended or their default replies. (The Apple Event Manager does, however, automatically dispose of a previously suspended Apple event and its default reply if the server later resumes processing of the Apple event by calling the AEResumeTheCurrentEvent function.) If your server application does not resume processing of a suspended Apple event, it is responsible for using the AEDisposeDesc function to dispose of both the Apple event and its default reply when your application has finished using them.
SPECIAL CONSIDERATIONS
If your application suspends handling of an Apple event it sends to itself, the Apple Event Manager immediately returns from the AESend call with the error code errAETimeout, regardless of whether the kAEQueueReply, kAEWaitReply, or kAENoReply flags were set, even if the timeout parameter is set to kNoTimeOut. The routine calling AESend should take the timeout error as confirmation that the event was sent.
As with other calls to AESend that return a timeout error, the handler continues to process the event nevertheless. The handler’s reply, if any, is provided in the reply event when the handling is completed. The Apple Event Manager provides no notification that the reply is ready. If no data has yet been placed in the reply event, the Apple Event Manager returns errAEReplyNotArrived when your application attempts to extract data from the reply.
RESULT CODEnoErr 0 No error
AEResumeTheCurrentEvent
You can use the AEResumeTheCurrentEvent function to inform the Apple Event Manager that your application wants to resume the handling of a previously suspended Apple event or that it has completed the handling of the Apple event.
FUNCTION AEResumeTheCurrentEvent
(theAppleEvent, reply: AppleEvent;
dispatcher: EventHandlerProcPtr;
handlerRefcon: LongInt): OSErr;
theAppleEvent
The Apple event to be resumed.
reply The default reply provided by the Apple Event Manager for the Apple event.
dispatcher
One of the following:
n a pointer to a routine for handling the event
n the kAEUseStandardDispatch constant, which tells the Apple Event Manager to dispatch the resumed event using the standard dispatching scheme it uses for other Apple events
n the kAENoDispatch constant, which tells the Apple Event Manager that the Apple event has been completely processed and need not be dispatched
handlerRefcon
If the value of the dispatcher parameter is not kAEUseStandardDispatch, this parameter is the reference constant passed to the handler when the handler is called. If the value of the dispatcher parameter is kAEUseStandardDispatch, the Apple Event Manager ignores the handlerRefcon parameter and instead passes the reference constant stored in the Apple event dispatch table entry for the Apple event. (You may wish to pass the same reference constant that is stored in the Apple event dispatch table. If so, call the AEGetEventHandler function.)
DESCRIPTION
When your application calls the AEResumeTheCurrentEvent function, the Apple Event Manager resumes handling the specified Apple event using the handler specified in the dispatcher parameter, if any. If kAENoDispatch is specified in the dispatcher parameter, AEResumeTheCurrentEvent simply informs the Apple Event Manager that the specified event has been handled.
SPECIAL CONSIDERATIONS
An Apple event handler that suspends an event should not immediately call AEResumeTheCurrentEvent, or else the handler will generate an error. Instead, the handler should return just after suspending the event.
When your application calls AEResumeTheCurrentEvent for an event that was not directly dispatched, the Apple Event Manager disposes of the event and the reply, just as it normally does, after the event handler returns to AEProcessAppleEvent. Make sure all processing involving the event or the reply has been completed before your application calls AEResumeTheCurrentEvent. Do not call AEResumeTheCurrentEvent for an event that was not suspended.
When your application calls AEResumeTheCurrentEvent for an event that was directly dispatched, your application is responsible for disposing of the original event and the reply, since it is acts as both the server and the client.
RESULT CODEnoErr 0 No error
AESetTheCurrentEvent
You can use the AESetTheCurrentEvent function to specify the Apple event to be handled.
FUNCTION AESetTheCurrentEvent (theAppleEvent: AppleEvent): OSErr;
theAppleEvent
The Apple event to be handled.
DESCRIPTION
There is usually no reason for your application to use the AESetTheCurrentEvent function. Instead of calling this function, your application should let the Apple Event Manager set the current Apple event through the dispatch tables.
If you need to avoid the dispatch tables, you must use the AESetTheCurrentEvent function only in the following way:
1. Your application suspends handling of an Apple event by calling the AESuspendTheCurrentEvent function.
2. Your application calls the AESetTheCurrentEvent function. This informs the Apple Event Manager that your application is handling the suspended Apple event. In this way, any routines that call the AEGetTheCurrentEvent function can ascertain which event is currently being handled.
3. When your application finishes handling the Apple event, it calls the AEResumeTheCurrentEvent function with the value kAENoDispatch to tell the Apple Event Manager that the event has been processed and need not be dispatched.
RESULT CODEnoErr 0 No error
AEGetTheCurrentEvent
You can use the AEGetTheCurrentEvent function to get the Apple event that is currently being handled.
FUNCTION AEGetTheCurrentEvent
(VAR theAppleEvent: AppleEvent): OSErr;
theAppleEvent
The Apple event that is currently being handled; if no Apple event is currently being handled, AEGetTheCurrentEvent returns a null descriptor record in this parameter.
DESCRIPTION
In many applications, the handling of an Apple event involves one or more long chains of calls to internal routines. The AEGetTheCurrentEvent function makes it unnecessary for these calls to include the current Apple event as a parameter; the routines can simply call AEGetTheCurrentEvent to get the current Apple event when it is needed.
You can also use the AEGetTheCurrentEvent function to make sure that no Apple event is currently being handled. For example, suppose your application always uses an application-defined routine to delete a file. That routine can first call AEGetTheCurrentEvent and delete the file only if AEGetTheCurrentEvent returns a null descriptor record (that is, only if no Apple event is currently being handled).
RESULT CODEnoErr 0 No error
Getting the Sizes and Descriptor Types of Descriptor Records
The Apple Event Manager provides four routines that allow you to get the sizes and descriptor types of descriptor records that are not part of an Apple event record. The AESizeOfNthItem function returns the size and descriptor type of a descriptor record in a descriptor list.The AESizeOfKeyDesc function returns the size and descriptor type of a keyword-specified descriptor record in an AE record. You can get the size and descriptor type of an Apple event parameter or Apple event attribute using the AESizeOfParam and AESizeOfAttribute functions.
AESizeOfNthItem
You can use the AESizeOfNthItem function to get the size and descriptor type of a descriptor record in a descriptor list.
FUNCTION AESizeOfNthItem (theAEDescList: AEDescList;
index: LongInt; VAR typeCode: DescType;
VAR dataSize: Size): OSErr;
theAEDescList
The descriptor list containing the descriptor record.
index The position of the descriptor record in the list (for example, 2 specifies the second descriptor record).
typeCode The descriptor type of the descriptor record.
dataSize The length (in bytes) of the data in the descriptor record.
RESULT CODESnoErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAEReplyNotArrived –1718 Reply has not yet arrived
AESizeOfKeyDesc
You can use the AESizeOfKeyDesc function to get the size and descriptor type of a keyword-specified descriptor record in an AE record.
FUNCTION AESizeOfKeyDesc (theAERecord: AERecord;
theAEKeyword: AEKeyword;
VAR typeCode: DescType;
VAR dataSize: Size): OSErr;
theAERecord
The AE record containing the desired keyword-specified descriptor record.
theAEKeyword
The keyword that specifies the desired descriptor record.
typeCode The descriptor type of the keyword-specified descriptor record.
dataSize The length, in bytes of the data in the keyword-specified descriptor record.
RESULT CODESnoErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
AESizeOfParam
You can use the AESizeOfParam function to get the size and descriptor type of an Apple event parameter.
FUNCTION AESizeOfParam (theAppleEvent: AppleEvent; theAEKeyword:
AEKeyword; VAR typeCode: DescType;
VAR dataSize: Size): OSErr;
theAppleEvent
The Apple event containing the parameter.
theAEKeyword
The keyword that specifies the desired parameter.
typeCode The descriptor type of the Apple event parameter.
dataSize The length, in bytes, of the data in the Apple event parameter.
RESULT CODESnoErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
AESizeOfAttribute
You can use the AESizeOfAttribute function to get the size and descriptor type of an Apple event attribute.
FUNCTION AESizeOfAttribute (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
VAR typeCode: DescType;
VAR dataSize: Size): OSErr;
theAppleEvent
The Apple event containing the desired attribute.
theAEKeyword
The keyword that specifies the attribute.
typeCode The descriptor type of the attribute.
dataSize The length, in bytes, of the data in the attribute.
RESULT CODESnoErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
Deleting Descriptor Records
The Apple Event Manager provides three functions that allow you to delete descriptor records. The AEDeleteItem, AEDeleteKeyDesc, and AEDeleteParam functions allow you to delete descriptor records from a descriptor list, an AE record, and an Apple event parameter, respectively.
AEDeleteItem
You can use the AEDeleteItem function to delete a descriptor record from a descriptor list. All subsequent descriptor records will then move up one place.
FUNCTION AEDeleteItem (theAEDescList: AEDescList;
index: LongInt): OSErr;
theAEDescList
The descriptor list containing the descriptor record to be deleted.
index The position of the descriptor record to delete (for example, 2 specifies the second item).
RESULT CODESnoErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
AEDeleteKeyDesc
You can use the AEDeleteKeyDesc function to delete a keyword-specified descriptor record from an AE record.
FUNCTION AEDeleteKeyDesc (theAERecord: AERecord;
theAEKeyword: AEKeyword): OSErr;
theAERecord
The AE record containing the keyword-specified descriptor record to be deleted.
theAEKeyword
The keyword that specifies the descriptor record to be deleted.
RESULT CODESnoErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
AEDeleteParam
You can use the AEDeleteParam function to delete an Apple event parameter.
FUNCTION AEDeleteParam (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword): OSErr;
theAppleEvent
The Apple event containing the parameter to be deleted.
theAEKeyword
The keyword that specifies the parameter to be deleted.
RESULT CODESnoErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
Deallocating Memory for Descriptor Records
The AEDisposeDesc function deallocates the memory used by a descriptor record. Because all Apple event structures (except for keyword-specified descriptor records) are descriptor records, you can use AEDisposeDesc for any of them.
AEDisposeDesc
You can use the AEDisposeDesc function to deallocate the memory used by a descriptor record.
FUNCTION AEDisposeDesc (VAR theAEDesc: AEDesc): OSErr;
theAEDesc The descriptor record to deallocate. The function returns a null descriptor record in this parameter. If you pass a null descriptor record in this parameter, AEDisposeDesc returns noErr.
RESULT CODEnoErr 0 No error
SEE ALSO
For more information about using AEDisposeDesc, see “Disposing of Apple Event Data Structures,” which begins on page 4-39.
Coercing Descriptor Types
The Apple Event Manager provides two functions that allow you to coerce descriptor types. The AECoercePtr function takes a pointer to data and a desired descriptor type and attempts to coerce the data to a descriptor record of the desired descriptor type. The AECoerceDesc function attempts to coerce the data in an existing descriptor record to another descriptor type.
AECoercePtr
You can use the AECoercePtr function to coerce data to a desired descriptor type. If successful, it creates a descriptor record containing the newly coerced data.
FUNCTION AECoercePtr (typeCode: DescType; dataPtr: Ptr;
dataSize: Size; toType: DescType;
VAR result: AEDesc): OSErr;
typeCode The descriptor type of the source data.
dataPtr A pointer to the data to be coerced.
dataSize The length, in bytes, of the data to be coerced.
toType The desired descriptor type of the resulting descriptor record.
result The resulting descriptor record.
DESCRIPTION
The AECoercePtr function creates a new descriptor record by coercing the specified data to a descriptor record of the specified descriptor type. You should use the AEDisposeDesc function to dispose of the resulting descriptor record once you are finished using it.
If AECoercePtr returns a nonzero result code, it returns a null descriptor record unless the Apple Event Manager is not available because of limited memory.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
SEE ALSO
For a description of the AEDisposeDesc function, see page 4-94.
AECoerceDesc
You can use the AECoerceDesc function to coerce the data in a descriptor record to another descriptor type.
FUNCTION AECoerceDesc (theAEDesc: AEDesc; toType: DescType;
VAR result: AEDesc): OSErr;
theAEDesc The descriptor record whose data is to be coerced.
toType The desired descriptor type of the resulting descriptor record.
result The resulting descriptor record.
DESCRIPTION
The AECoerceDesc function attempts to create a new descriptor record by coercing the specified descriptor record. Your application is responsible for using the AEDisposeDesc function to dispose of the resulting descriptor record once you are finished using it.
If AECoerceDesc returns a nonzero result code, it returns a null descriptor record (a descriptor record of type typeNull, which does not contain any data) unless the Apple Event Manager is not available because of limited memory.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to requested descriptor type
SEE ALSO
For a list of the descriptor types for which the Apple Event Manager provides coercions, see Table 4-1, which begins on page 4-43.
Creating and Managing the Coercion Handler Dispatch Tables
The Apple Event Manager provides three functions that allow you to create and manage the coercion handler dispatch tables. The AEInstallCoercionHandler function installs a coercion handler routine in either the application or system coercion dispatch table. The AEGetCoercionHandler function returns the handler for a specified descriptor type coercion. The AERemoveCoercionHandler function removes a coercion handler from either the application or system coercion table.
AEInstallCoercionHandler
You can use the AEInstallCoercionHandler function to install a coercion handler routine in either the application or system coercion handler dispatch table.
FUNCTION AEInstallCoercionHandler (fromType: DescType;
toType: DescType;
handler: ProcPtr;
handlerRefcon: LongInt;
fromTypeIsDesc: Boolean;
isSysHandler: Boolean): OSErr;
fromType The descriptor type of the data coerced by the handler.
toType The descriptor type of the resulting data. If there was already an entry in the specified coercion handler table for the same source descriptor type and result descriptor type, the existing entry is replaced.
handler A pointer to the coercion handler. Note that a handler in the system coercion table must reside in the system heap; thus, if the value of the isSysHandler parameter is TRUE, the handler parameter should point to a location in the system heap. Otherwise, if you put your system handler code in your application heap, you should use AERemoveCoercionHandler to remove the handler when your application quits.
handlerRefcon
A reference constant passed by the Apple Event Manager to the handler each time the handler is called. If your handler doesn’t expect a reference constant, use 0 as the value of this parameter.
fromTypeIsDesc
Specifies the form of the data to be coerced. If the value of this parameter is TRUE, the coercion handler expects the data to be passed as a descriptor record. If the value is FALSE, the coercion handler expects a pointer to the data. Because it is more efficient for the Apple Event Manager to provide a pointer to data than to a descriptor record, all coercion routines should accept a pointer to data if possible.
isSysHandler
Specifies the coercion table to which the handler is added. If the value of this parameter is TRUE, the handler is added to the system coercion table and made available to all applications. If the value is FALSE, the handler is added to the application coercion table. Note that a handler in the system coercion table must reside in the system heap; thus, if the value of the isSysHandler parameter is TRUE, the handler parameter must point to a location in the system heap.
DESCRIPTION
Before using AEInstallCoercionHandler to install a handler for a particular descriptor type into the system coercion handler dispatch table, use the AEGetCoercionHandler function to determine whether the table already contains a coercion handler for that descriptor type. If an entry exists, AEGetCoercionHandler returns a reference constant and a pointer to that handler. Chain these to your coercion handler by providing, in the handlerRefcon parameter of AEInstallCoercionHandler, pointers to the previous handler and its reference constant. If your coercion handler returns the error errAECoercionFail, use these pointers to call the previous handler. If you remove your system coercion handler, be sure to reinstall the chained handlers.
SPECIAL CONSIDERATIONS
Before an application calls a system coercion handler, system software has set up the A5 register for the calling application. For this reason, if you provide a system coercion handler, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system handler may crash.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
AEGetCoercionHandler
You can use the AEGetCoercionHandler function to get the handler for a specified descriptor type coercion.
FUNCTION AEGetCoercionHandler (fromType: DescType;
toType: DescType;
VAR handler: ProcPtr;
VAR handlerRefcon: LongInt;
VAR fromTypeIsDesc: Boolean;
isSysHandler: Boolean): OSErr;
fromType The descriptor type of the data coerced by the handler.
toType The descriptor type of the resulting data.
handler A pointer to the desired coercion handler.
handlerRefcon
The reference constant for the desired handler. The Apple Event Manager passes this reference constant to the handler each time the handler is called.
fromTypeIsDesc
If the AEGetCoercionHandler function returns TRUE in this parameter, the coercion handler expects the data to be passed as a descriptor record. If the function returns FALSE, the coercion handler expects a pointer to the data.
isSysHandler
Specifies the coercion table from which to get the handler. If the value of this parameter is TRUE, the handler is taken from the system coercion table. If the value is FALSE, the handler is taken from the application coercion table.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEHandlerNotFound –1717 No coercion handler found
AERemoveCoercionHandler
You can use the AERemoveCoercionHandler function to remove a coercion handler from either the application or system coercion handler dispatch table.
FUNCTION AERemoveCoercionHandler (fromType: DescType;
toType: DescType;
handler: ProcPtr;
isSysHandler: Boolean): OSErr;
fromType The descriptor type of the data coerced by the handler.
toType The descriptor type of the resulting data.
handler A pointer to the coercion handler. Although the fromType and toType parameters would be sufficient to identify the handler to be removed, providing the handler parameter is a safeguard to ensure that you remove the correct handler.
isSysHandler
The coercion table from which to remove the handler. If the value of this parameter is TRUE, the handler is removed from the system coercion table. If the value is FALSE, the handler is removed from the application coercion dispatch table.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEHandlerNotFound –1717 No coercion handler found
Creating and Managing the Special Handler Dispatch Tables
The Apple Event Manager provides three functions that allow you to create and manage the special handler dispatch tables. The AEInstallSpecialHandler function installs an entry for a special handler in either the application or system special handler dispatch table. The AEGetSpecialHandler function returns the handler for a specified special handler. The AERemoveSpecialHandler function removes a special handler from either the application or system special handler dispatch table.
You can also use the AEInstallSpecialHandler, AEGetSpecialHandler, and AERemoveSpecialHandler functions to install, get, and remove object callback functions—including system object callback functions, which cannot be installed with the AESetObjectCallbacks function. When calling any of these three functions, use one of the following constants as the value of the functionClass parameter to specify the object callback function:Object callback function Constant
Object-counting function keyAECountProc
Object-comparison function keyAECompareProc
Token disposal function keyDiposeTokenProc
Error callback function keyAEGetErrDescProc
Mark token function keyAEMarkTokenProc
Object-marking function keyAEMarkProc
Mark-adjusting function keyAEAdjustMarksProc
You can also use the AERemoveSpecialHandler function to disable all the Apple Event Manager routines that support object specifier records. To do this, specify the constant keySelectProc in the functionClass parameter as described on page 4-102.
AEInstallSpecialHandler
You can use the AEInstallSpecialHandler function to install a special handler in either the application or system special handler dispatch table.
FUNCTION AEInstallSpecialHandler (functionClass: AEKeyword;
handler: ProcPtr;
isSysHandler: Boolean): OSErr;
functionClass
The keyword for the special handler that is installed. The keyPreDispatch constant identifies a handler with the same parameters as an Apple event handler called immediately before the Apple Event Manager dispatches an Apple event. Any of the constants for object callback functions listed above can also be specified in this parameter. If there was already an entry in the specified special handler dispatch table for the same value of functionClass, it is replaced.
handler A pointer to the special handler. Note that a handler in the system special handler dispatch table must reside in the system heap; thus, if the value of the isSysHandler parameter is TRUE, the handler parameter should point to a location in the system heap. Otherwise, if you put your system handler code in your application heap, use AERemoveSpecialHandler to remove the handler when your application quits.
isSysHandler
The special handler dispatch table to which to add the handler. If the value of this parameter is TRUE, the handler is added to the system handler dispatch table and made available to all applications. If the value is FALSE, the handler is added to the application handler table.
DESCRIPTION
The AEInstallSpecialHandler function creates an entry in either your application’s special handler dispatch table or the system special handler dispatch table. You must supply parameters that specify the keyword for the special handler that is installed, the handler routine, and whether the handler is to be added to the system special handler dispatch table or your application’s special handler dispatch table.
SPECIAL CONSIDERATIONS
Before an application calls a system special handler, system software has set up the A5 register for the calling application. For this reason, a system special handler should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system handler may crash.
RESULT CODESnoErr 0 No error
paramErr –50 Parameter error (handler pointer is NIL or odd)
memFullErr –108 Not enough room in heap zone
errAENotASpecialFunction –1714 Wrong keyword for a special function
AEGetSpecialHandler
You can use the AEGetSpecialHandler function to get a specified special handler.
FUNCTION AEGetSpecialHandler (functionClass: AEKeyword;
VAR handler: ProcPtr;
isSysHandler: Boolean): OSErr;
functionClass
The keyword for the special handler that is installed. The keyPreDispatch constant identifies a handler with the same parameters as an Apple event handler that is called immediately before the Apple Event Manager dispatches an Apple event. Any of the constants for object callback functions listed on page 4-100 can also be specified in this parameter.
handler A pointer to the special handler.
isSysHandler
Specifies the special handler dispatch table from which to get the handler. If the value of this parameter is TRUE, the handler is taken from the system special handler dispatch table. If the value is FALSE, the handler is taken from the application’s special handler dispatch table.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAENotASpecialFunction –1714 Wrong keyword for a special handler
AERemoveSpecialHandler
You can use the AERemoveSpecialHandler function to remove a handler from a special handler table.
FUNCTION AERemoveSpecialHandler (functionClass: AEKeyword;
handler: ProcPtr;
isSysHandler: Boolean): OSErr;
functionClass
The keyword for the special handler to be removed. In addition to the constants for object callback functions listed on page 4-100, two other values are allowed for the functionClass parameter: keyPreDispatch and keySelectProc. The keyPreDispatch constant identifies a handler with the same parameters as an Apple event handler that is called immediately before the Apple Event Manager dispatches an Apple event. The keySelectProc constant indicates that you want to disable the Object Support Library—that is, all the routines described in the chapter “Resolving and Creating Object Specifier Records” in this book (see the description that follows for more information).
handler A pointer to the special handler to be removed. Although the functionClass parameter would be sufficient to identify the handler to be removed, providing the handler parameter is a safeguard that you remove the correct handler.
isSysHandler
Specifies the special handler dispatch table from which to remove the handler. If the value of this parameter is TRUE, the handler is taken from the system special handler dispatch table. If the value is FALSE, the handler is removed from the application special handler dispatch table.
DESCRIPTION
In addition to using the AERemoveSpecialHandler function to remove specific special handlers, you can use the function to disable, within your application only, all Apple Event Manager routines that support Apple event objects—that is, all the routines available to your application as a result of linking the Object Support Library (OSL) and calling the AEObjectInit function.
An application that expects its copy of the OSL to move after it is installed—for example, an application that keeps it in a stand-alone code resource—would need to do this. When an application calls AEObjectInit to initialize the OSL, the OSL installs the addresses of its routines as extensions to the pack. If those routines move, the addresses become invalid.
To disable the OSL, you should pass the keyword keySelectProc in the functionClass parameter, NIL in the handler parameter, and FALSE in the isSysHandler parameter. Once you have called the AERemoveSpecialHandler function with these parameters, subsequent calls by your application to any of the Apple Event Manager routines that support Apple event objects will return errors. To initialize the OSL after disabling it with the AERemoveSpecialHandler function, your application must call AEObjectInit again.
If you expect to initialize the OSL and disable it several times, you should call AERemoveObjectAccessor to remove your application’s object accessor functions from your application’s object accessor dispatch table before you call AERemoveSpecialHandler.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAENotASpecialFunction –1714 Wrong keyword for a special function
Getting Information About the Apple Event Manager
The AEManagerInfo routine allows you to get two kinds of information related to Apple events on the current computer: the number of processes currently recording Apple events and the version of the Apple Event Manager. If you decide to make your application recordable, this information may be useful when your application is responding to Apple events that it sends to itself.
You can find out whether the Apple Event Manager is available in system software by using the Gestalt function. See page 4-4 for details.
AEManagerInfo
You can use the AEManagerInfo function to obtain information about the version of the Apple Event Manager currently available or the number of processes that are currently recording Apple events. This function is available only in version 1.01 and later versions of the Apple Event Manager.
FUNCTION AEManagerInfo (keyword: AEKeyword;
VAR result: LongInt): OSErr;
keyword A value that determines what kind of information AEManagerInfo returns. The value can be represented by one of these constants:
CONST keyAERecorderCount = 'recr';
keyAEVersion = 'vers';
result If the value of the keyword parameter is keyAERecorderCount, this parameter is an integer that indicates the number of processes that are currently recording Apple events. If the value of the keyword parameter is keyAEVersion, this parameter is an integer that provides information about the version of the Apple Event Manager available on the current computer, using the same format as a 'vers' resource.
RESULT CODEnoErr 0 No error
SEE ALSO
For information about using the AEManagerInfo function to check whether Apple event recording is on or not, see the chapter “Recording Apple Events” in this book.
For information about using Gestalt to determine whether the Apple Event Manager is available, see “Handling Apple Events” on page 4-4.
For information about the 'vers' resource, see the chapter “Finder Interface” in Inside Macintosh: Macintosh Toolbox Essentials.
Application-Defined Routines
For each Apple event your application supports, you must provide an Apple event handler. The AEProcessAppleEvent function calls one of your Apple event handlers when it processes an Apple event. An Apple event handler (MyEventHandler) should perform any action described by the Apple event, add parameters to the reply Apple event if appropriate, and return a result code.
You can also provide your own coercion handlers to coerce data to descriptor types other than those for which the Apple Event Manager provides coercion handling. The MyCoercePtr function accepts a pointer to data and returns a descriptor record, and the MyCoerceDesc function accepts a descriptor record and returns a descriptor record.
MyEventHandler
An Apple event handler has the following syntax:
FUNCTION MyEventHandler (theAppleEvent: AppleEvent;
reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
theAppleEvent
The Apple event to handle.
reply The default reply Apple event provided by the Apple Event Manager.
handlerRefcon
The reference constant stored in the Apple event dispatch table for the Apple event.
DESCRIPTION
An Apple event handler should extract any parameters and attributes from the Apple event, perform the requested action, and add parameters to the reply Apple event if appropriate.
Your handler should always set its function result to noErr if it successfully handles the Apple event. If an error occurs, your handler should return either errAEEventNotHandled or some other nonzero result code. If the error occurs because your application cannot understand the event, return errAEEventNotHandled, in case a handler in the system special handler or system Apple event dispatch tables might be able to handle the event. If the error occurs because the event is impossible to handle as specified, return the result code returned by whatever function caused the failure, or whatever other result code is appropriate.
For example, suppose your application receives a Get Data event that requests the name of the current printer, and your application cannot handle such an event. In this situation, you should return errAEEventNotHandled in case another handler available to the Apple Event Manager can handle the event. This strategy allows users to take advantage of system capabilities from within your application via system handlers.
However, if your application cannot handle a Get Data event that requests the fifth paragraph in a document because the document contains only four paragraphs, you should return some other nonzero error, because further attempts to handle the event are pointless.
If your Apple event handler calls the AEResolve function and AEResolve calls an object accessor function in the system object accessor dispatch table, your Apple event handler may not recognize the descriptor type of the token returned by the function. In this case, your handler should return the result code errAEUnknownObjectType. When your handler returns this result code, the Apple Event Manager attempts to locate a system Apple event handler that can recognize the token.
SEE ALSO
For more information about Apple event handlers, see “Writing Apple Event Handlers” on page 4-33.
For a discussion of the dispatching of object accessor functions and the use of the result code errAEUnknownObjectType, see “Installing Entries in the Object Accessor Dispatch Tables,” which begins on page 6-21.
MyCoercePtr
A coercion handler that accepts a pointer to data has the following syntax:
FUNCTION MyCoercePtr (typeCode: DescType; dataPtr: Ptr;
dataSize: Size; toType: DescType;
handlerRefcon: LongInt;
VAR result: AEDesc): OSErr;
typeCode The descriptor type of the original data.
dataPtr A pointer to the data to coerce.
dataSize The length, in bytes, of the data to coerce.
toType The desired descriptor type for the resulting descriptor record.
handlerRefcon
A reference constant that is stored in the coercion dispatch table entry for the handler and passed to the handler by the Apple Event Manager whenever the handler is called.
result The resulting descriptor record.
DESCRIPTION
Your coercion handler should coerce the data to the desired descriptor type and return the resulting data in the descriptor record specified by the result parameter. Your handler should return the noErr result code if your handler successfully performs the coercion, and a nonzero result code otherwise.
SEE ALSO
For more information, see “Writing and Installing Coercion Handlers” on page 4-41.
MyCoerceDesc
A coercion handler that accepts a descriptor record has the following syntax:
FUNCTION MyCoerceDesc (theAEDesc: AEDesc; toType: DescType;
handlerRefcon: LongInt;
VAR result: AEDesc): OSErr;
theAEDesc The descriptor record that contains the data to be coerced.
toType The desired descriptor type for the resulting descriptor record.
handlerRefcon
A reference constant that is stored in the coercion dispatch table entry for the handler and passed to the handler by the Apple Event Manager whenever the handler is called.
result The resulting descriptor record.
DESCRIPTION
Your coercion handler should coerce the data in the descriptor record to the desired descriptor type and return the resulting data in the descriptor record specified by the result parameter. Your handler should return an appropriate result code.
SEE ALSO
For more information, see “Writing and Installing Coercion Handlers” on page 4-41.
Summary of Responding to Apple Events
Pascal Summary
Constants
CONST
gestaltAppleEventsAttr = 'evnt'; {selector for Apple events}
gestaltAppleEventsPresent = 0; {if this bit is set, then Apple }
{ Event Manager is available}
{Apple event descriptor types}
typeBoolean = 'bool'; {1-byte Boolean value}
typeChar = 'TEXT'; {unterminated string}
typeSMInt = 'shor'; {16-bit integer}
typeInteger = 'long'; {32-bit integer}
typeSMFloat = 'sing'; {SANE single}
typeFloat = 'doub'; {SANE double}
typeLongInteger = 'long'; {32-bit integer}
typeShortInteger = 'shor'; {16-bit integer}
typeLongFloat = 'doub'; {SANE double}
typeShortFloat = 'sing'; {SANE single}
typeExtended = 'exte'; {SANE extended}
typeComp = 'comp'; {SANE comp}
typeMagnitude = 'magn'; {unsigned 32-bit integer}
typeAEList = 'list'; {list of descriptor records}
typeAERecord = 'reco'; {list of keyword-specified }
noPortErr –903 Client hasn’t set 'SIZE' resource to indicate awareness of high-level events
destPortErr –906 Server hasn’t set 'SIZE' resource to indicate awareness of high-level events, or else is not present
sessClosedErr –917 The kAEDontReconnect flag in the sendMode parameter was set, and the server quit and then restarted
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAECorruptData –1702 Data in an Apple event could not be read
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
errAENewerVersion –1706 Need a newer version of the Apple Event Manager
errAENotAppleEvent –1707 Event is not an Apple event
errAEEventNotHandled –1708 Event wasn’t handled by an Apple event handler
errAEReplyNotValid –1709 AEResetTimer was passed an invalid reply
errAEUnknownSendMode –1710 Invalid sending mode was passed
errAEWaitCanceled –1711 User canceled out of wait loop for reply or receipt
errAETimeout –1712 Apple event timed out
errAENoUserInteraction –1713 No user interaction allowed
errAENotASpecialFunction –1714 The keyword is not valid for a special function
errAEParamMissed –1715 Handler cannot understand a parameter the client considers required
errAEUnknownAddressType –1716 Unknown Apple event address type
errAEHandlerNotFound –1717 No handler found for an Apple event or a coercion, or no object callback function found
errAEReplyNotArrived –1718 Reply has not yet arrived
errAEIllegalIndex –1719 Not a valid list index
errAEImpossibleRange –1720 The range is not valid because it is impossible for a range to include the first and last objects that were specified; an example is a range in which the offset of the first object is greater than the offset of the last object
errAEWrongNumberArgs –1721 The number of operands provided for the kAENot logical operator is not 1
errAEAccessorNotFound –1723 There is no object accessor function for the specified object class and token descriptor type
errAENoSuchLogical –1725 The logical operator in a logical descriptor record is not kAEAnd, kAEOr, or kAENot
errAEBadTestKey –1726 The descriptor record in a test key is neither a comparison descriptor record nor a logical descriptor record
errAENotAnObjectSpec –1727 The objSpecifier parameter of AEResolve is not an object specifier record
errAENoSuchObject –1728 A run-time resolution error, for example: object specifier record asked for the third element, but there are only two
errAENegativeCount –1729 Object-counting function returned negative value
errAEEmptyListContainer –1730 The container for an Apple event object is specified by an empty list
errAEUnknownObjectType –1731 Descriptor type of token returned by AEResolve is not known to server application
errAERecordingIsAlreadyOn –1732 Attempt to turn recording on when it is already on
Listing 5-0
Table 5-0
Creating and Sending Apple Events
Contents
Creating an Apple Event5-3
Adding Parameters to an Apple Event5-5
Specifying Optional Parameters for an Apple Event5-7
Specifying a Target Address5-10
Creating an Address Descriptor Record5-11
Addressing an Apple Event for Direct Dispatching5-13
Sending an Apple Event5-13
Dealing With Timeouts5-20
Writing an Idle Function5-21
Writing a Reply Filter Function5-24
Reference to Creating and Sending Apple Events5-24
Routines for Creating and Sending Apple Events5-25
Creating Apple Events5-25
Creating and Duplicating Descriptor Records5-26
Creating Descriptor Lists and AE Records5-28
Adding Items to Descriptor Lists5-29
Adding Data and Descriptor Records to AE Records5-32
Adding Parameters and Attributes to Apple Events5-33
Sending Apple Events5-37
Application-Defined Routines5-41
Summary of Creating and Sending Apple Events5-44
Pascal Summary5-44
Constants5-44
Data Types5-48
Routines for Creating and Sending Apple Events5-50
Application-Defined Routines5-51
C Summary5-51
Constants5-51
Data Types5-56
Routines for Creating and Sending Apple Events5-57
Application-Defined Routines5-59
Assembly-Language Summary5-59
Trap Macros5-59
Result Codes5-60
Creating and Sending Apple Events
This chapter describes how your application can use the Apple Event Manager to create and send Apple events. If you want to factor your application for recording, or if you want your application to send Apple events directly to other applications, you can use Apple Event Manager routines to create and send Apple events.
Before you read this chapter, you should be familiar with the chapters “Introduction to Interapplication Communication,” “Introduction to Apple Events,” and “Responding to Apple Events” in this book. If you are factoring your application, you should also be familiar with the chapter “Recording Apple Events” in this book.
This chapter provides the basic information you need to create and send Apple events from your application. To send core and functional-area Apple events, your application must also be able to create object specifier records. For information about object specifier records, see the chapter “Resolving and Creating Object Specifier Records” in this book.
To allow your application to send Apple events to applications on other computers, you may wish to use the PPCBrowser function, which is described in the chapter “Program-to-Program Communications Toolbox” in this book.
The first section in this chapter, “Creating an Apple Event,” describes how to
n create an Apple event
n add parameters to an Apple event
n specify optional Apple event parameters
n specify a target address
The section “Sending an Apple Event” describes how to
n send an Apple event
n deal with timeouts
n write an idle function
n write a reply filter function
Creating an Apple Event
You create an Apple event by using the AECreateAppleEvent function. You supply parameters that specify the event class and event ID, the target address, the return ID, and the transaction ID, and a buffer for the returned Apple event. The AECreateAppleEvent function creates and returns, in the buffer you specify, an Apple event with the attributes set as your application requested. You should not directly manipulate the contents of the Apple event; rather, use Apple Event Manager functions to add additional attributes or parameters to it.
The example that follows creates an imaginary Multiply event using the AECreateAppleEvent function.
The event class, specified by the kArithmeticClass constant, identifies this event as belonging to a class of Apple events for arithmetic operations. The event ID specifies the particular Apple event within the class—in this case, an Apple event that performs multiplication.
You specify the target of the Apple event in the third parameter to AECreateAppleEvent. The target address can identify an application on the local computer or another computer on the network. You can specify the address using a target ID record or session reference number. For processes on the local computer, you can also use a process serial number or application signature to specify the address. See “Specifying a Target Address” on page 5-10 for more information.
In the fourth parameter, you specify the return ID of the Apple event, which associates this Apple event with the server’s reply. The AECreateAppleEvent function assigns the specified return ID value to the keyReturnIDAttr attribute of the Apple event. If a server returns a standard reply Apple event (that is, an event of event class 'aevt' and event ID 'ansr') in response to this event, the Apple Event Manager assigns the reply event the same return ID. When you receive a reply Apple event, you can check the keyReturnIDAttr attribute to determine which outstanding Apple event the reply is responding to. You can use the kAutoGenerateReturnID constant to request that the Apple Event Manager generate a return ID that is unique to this session for the Apple event. Otherwise, you are responsible for making it unique.
The fifth parameter specifies the transaction ID attribute of the Apple event. A transaction is a sequence of Apple events that are sent back and forth between the client and server applications, beginning with the client’s initial request for a service. All Apple events that are part of one transaction must have the same transaction ID.
You can use a transaction ID to indicate that an Apple event is one of a sequence of Apple events related to a single transaction. The kAnyTransactionID constant indicates that the Apple event is not part of a transaction.
The AECreateAppleEvent function creates an Apple event with only the specified attributes and no parameters. To add parameters or additional attributes, you can use other Apple Event Manager functions.
Adding Parameters to an Apple Event
You can use the AEPutParamPtr or AEPutParamDesc function to add parameters to an Apple event. When you use either of these functions, the Apple Event Manager adds the specified parameter to the Apple event.
Use the AEPutParamPtr function when you want to add data specified in a buffer as the parameter of an Apple event. You specify the Apple event, the keyword of the parameter to add, the descriptor type, a buffer that contains the data, and the size of this buffer as parameters to the AEPutParamPtr function. The AEPutParamPtr function adds the data to the Apple event as a parameter with the specified keyword.
For example, this code adds a parameter to the Multiply event using the AEPutParamPtr function:
In this example, the Apple Event Manager adds the parameter containing the first number to the specified Apple event.
Use the AEPutParamDesc function to add a descriptor record to an Apple event. The descriptor record you specify must already exist. To create or get a descriptor record, you can use the AECreateDesc, AEDuplicateDesc, and other Apple Event Manager functions that return a descriptor record.
When you create a descriptor record using the AECreateDesc function, you specify the descriptor type, a buffer that contains the data, and the size of this buffer as parameters. The AECreateDesc function returns the descriptor record that describes the data.
This example creates a descriptor record for the second parameter of the Multiply event:
In this example, the AECreateDesc function creates a descriptor record with the typeLongInteger descriptor type and the data identified in the number2 variable.
Once you have created a descriptor record, you can use AEPutParamDesc to add the data to an Apple event parameter. You specify the Apple event to add the parameter to, the keyword of the parameter, and the descriptor record of the parameter as parameters to the AEPutParamDesc function.
This example adds a second parameter to the Multiply event using the AEPutParamDesc function:
This example adds the keyOperand2 keyword and the descriptor record created in the previous example as the second parameter to the specified Apple event.
You can also create a descriptor record without using Apple Event Manager routines. For example, this example generates an alias descriptor record from an existing alias handle:
WITH myAliasDesc DO
BEGIN
descriptorType := typeAlias;
dataHandle := myAliasHandle;
END;
Whatever method you use to create a descriptor record, you can add it to an Apple event parameter by using AEPutParamDesc.
After adding parameters to an Apple event, you can send the Apple event using the AESend function. See “Sending an Apple Event,” which begins on page 5-13, for information about using this function.
Specifying Optional Parameters for an Apple Event
The parameters for a given Apple event are listed in the Apple Event Registry: Standard Suites as either required or optional. Your application does not usually have to include Apple event parameters that are listed as optional; the target application uses default values for parameters that are listed as optional if your application does not provide them. The Apple Event Registry: Standard Suites defines the default value a target application should use for each optional parameter of a specific Apple event.
The guidelines listed in the Apple Event Registry: Standard Suites for which parameters should be considered optional and which should be considered required are not enforced by the Apple Event Manager. Instead, the source application indicates which Apple event parameters it considers optional by listing the keywords for those parameters in the keyOptionalKeywordAttr attribute.
The keyOptionalKeywordAttr attribute does not contain the optional parameters; it simply lists the keywords of any parameters for the Apple event that the source application wants to identify as optional. Although the source application is responsible for providing this information in the keyOptionalKeywordAttr attribute of an Apple event, it is not required to provide this attribute.
If a keyword for an Apple event parameter is not included in the keyOptionalKeywordAttr attribute, the source application expects the target application to understand the Apple event parameter identified by that keyword. If a target application cannot understand the parameter, it should return the result code errAEParamMissed and should not attempt to handle the event.
If a keyword for an Apple event parameter is included in the keyOptionalKeywordAttr attribute, the source application does not require the target application to understand the Apple event parameter identified by that keyword. If the target application cannot understand a parameter whose keyword is included in the keyOptionalKeywordAttr attribute, it should ignore that parameter and attempt to handle the Apple event as it normally does.
A source application can choose not to list the keyword for an Apple event parameter in the keyOptionalKeywordAttr attribute even if that parameter is listed in the Apple Event Registry: Standard Suites as an optional parameter. This has the effect of forcing the target application to treat the parameter as required for a particular Apple event. If the target application supports the parameter, it should handle the Apple event as the client application expects. If the target application does not support the parameter and calls an application-defined routine such as MyGotRequiredParams to check whether it has received all the required parameters, it finds that there’s another parameter that the client application considered required, and should return the result code errAEParamMissed.
If a source application wants a target application to attempt to handle an Apple event regardless of whether the target application supports a particular Apple event parameter included in that Apple event, the source application should list the keyword for that parameter in the keyOptionalKeywordAttr attribute.
It is up to the source application to decide whether to list a parameter that is described as optional in the Apple Event Registry: Standard Suites in the keyOptionalKeywordAttr attribute of an Apple event. For example, suppose a source application has extended the definition of the Print event to include an optional keyColorOrGrayscale parameter that specifies printing in color or gray scale rather than black and white. The source application might decide whether or not to list the keyword keyColorOrGrayscale in the keyOptionalKeywordAttr attribute according to the characteristics of the print request. If the source application requires the target application to print a document in color, the source application could choose not to add the keyword keyColorOrGrayscale to the keyOptionalKeywordAttr attribute; in this case, only target applications that supported the keyColorOrGrayscale parameter would attempt to handle the event. If the source application does not require the document printed in color, it could choose to add the keyword keyColorOrGrayscale to the keyOptionalKeywordAttr attribute; in this case, the target application will attempt to handle the event regardless of whether it supports the keyColorOrGrayscale parameter.
Your application can add optional parameters to an Apple event the same way it adds required parameters, using the AECreateDesc, AEPutParamPtr, and AEPutParamDesc functions as described in the previous section, “Adding Parameters to an Apple Event.” If your application chooses to provide the keyOptionalKeywordAttr attribute for an Apple event, it should first create a descriptor list that specifies the keywords of the optional parameters, then add it to the Apple event as a keyOptionalKeywordAttr attribute.
Listing 5-1 shows an application-defined routine, MyCreateOptionalKeyword, that creates the keyOptionalKeywordAttr attribute for the Create Publisher event.
Listing 5-1 Creating the optional keyword for the Create Publisher event
{create the keyOptionalKeywordAttr attribute and add it }
{ to the Create Publisher event}
myErr := AEPutAttributeDesc(createPubAppleEvent,
keyOptionalKeywordAttr,
optionalList);
END;
ignoreErr := AEDisposeDesc(optionalList);
MyCreateOptionalKeyword := myErr;
END;
The MyCreateOptionalKeyword function shown in Listing 5-1 adds to a descriptor list the keyword of each parameter that the source application considers optional. Each keyword is added as a descriptor record with the descriptor type typeKeyword. The function specifies that the target application can handle the Create Publisher event without supporting parameters identified by the keywords keyDirectObject and keyAEEditionFileLoc. (These are the parameters that specify the Apple event object to publish and the location of the edition container; if these parameters are missing, the target application creates a publisher for the current selection using the application’s default edition container.) After adding these keywords to the descriptor list, the function creates the keyOptionalKeywordAttr attribute using the AEPutAttributeDesc function.
Typically a target application does not examine the keyOptionalKeywordAttr attribute directly. Instead, a target application that supports a parameter listed as optional in the Apple Event Registry: Standard Suites attempts to extract it from the Apple event (using AEGetParamDesc, for example). If it can’t extract the parameter, the target application uses the default value, if any, listed in the Apple Event Registry. A target application can use the keyMissedKeywordAttr attribute to return the first required parameter (that is, considered required by the source application), if any, that it did not retrieve from the Apple event. The keyMissedKeywordAttr attribute does not return any parameters whose keywords are listed in the keyOptionalKeywordAttr attribute of the Apple event.
Specifying a Target Address
When you create an Apple event, you must specify the address of the target. The target address identifies the particular application or process to which you want to send the Apple event. You can send Apple events to applications on the local computer or on remote computers on the network.
These are the descriptor types that identify the four methods of addressing an Apple event:typeApplSignature The application signature of the target
typeSessionID The session reference number of the target
typeTargetID The target ID record of the target
typeProcessSerialNumber The process serial number of the target
To address an Apple event to a target on a remote computer on the network, you must use either the typeSessionID or typeTargetID descriptor type.
If your application sends an Apple event to itself, it should address the Apple event using a process serial number of kCurrentProcess. This is the fastest way for your application to send an Apple event to itself. For more information, see “Addressing an Apple Event for Direct Dispatching” on page 5-13.
You can use any of the four address types when sending an Apple event to another application on the local computer. The chapter “Event Manager” in Inside Macintosh: Macintosh Toolbox Essentials describes all four types of addresses. Your application can also use another address type if it provides a coercion handler that coerces the address type into one of the four address types that the Apple Event Manager recognizes. See “Writing and Installing Coercion Handlers,” which begins on page 4-41, for more information.
To allow the user to choose the target of an Apple event, use the PPCBrowser function. This function presents a standard user interface for choosing a target application, much as the Standard File Package provides a standard user interface for opening and saving files. The PPCBrowser function returns, in a target ID record, information about the application the user chose. Listing 5-3 on page 5-12 shows how to use the PPCBrowser function to let the user choose a target.
Creating an Address Descriptor Record
You specify the address using an address descriptor record (a descriptor record of data type AEAddressDesc). You must create a descriptor record of this type and then add it to the Apple event using the AECreateAppleEvent function.
You can use the AECreateDesc function to create address descriptor records for any of the four types of target addresses. Listing 5-2 shows four possible ways to create an address, each using a different address type.
To create an address descriptor record, specify the following as parameters to AECreateDesc: the descriptor type for the address, a pointer to the buffer containing the address, and the size of the buffer. The AECreateDesc function returns an address descriptor record with the specified characteristics.
After creating an address, you can specify it as a parameter to the AECreateAppleEvent function. See “Creating an Apple Event,” which begins on page 5-3, for an example using the AECreateAppleEvent function.
When you specify an address to the AECreateAppleEvent function, the Apple Event Manager stores the address in the keyAddressAttr attribute of the Apple event.
If you use the PPCBrowser function to allow the user to choose an Apple event’s target, your application must create a target ID record based on the user’s choice. Listing 5-3 shows how to create a target ID record using the information returned from the PPCBrowser function and create an address descriptor record using the AECreateDesc function.
Listing 5-3 Specifying a target address in an Apple event by using the PPCBrowser function
FUNCTION MyGetTargetAddress (myPrompt: Str255; myAppStr: Str255;
VAR myPortInfo: PortInfoRec;
VAR targetAddress: AEAddressDesc;
VAR toTargetID: targetID): OSErr;
VAR
myErr: OSErr;
BEGIN
{use PPCBrowser to let user choose the target}
myErr := PPCBrowser(myPrompt, myAppStr, FALSE,
toTargetID.location,
myPortInfo, NIL, '');
MyGetTargetAddress := myErr;
IF myErr <> noErr THEN Exit(MyGetTargetAddress);
toTargetID.name := myPortInfo.name;
{create the descriptor record for the target address}
See the chapter “Program-to-Program Communications Toolbox” in this book for more information on using the PPCBrowser function.
Addressing an Apple Event for Direct Dispatching
As described in the chapter “Recording Apple Events” in this book, a recordable application must send itself Apple events in response to user actions. Your application can send itself Apple events by using an address descriptor record of descriptor type typeProcessSerialNumber with the lowLongOfPSN field set to kCurrentProcess and the highLongOfPSN set to 0. The Apple Event Manager processes such Apple events immediately, executing the appropriate Apple event handler directly without going through the normal event-processing sequence. For this reason, your application will not appear to run more slowly when it sends Apple events to itself.
Apple events your application sends to itself this way do not appear in your application’s high-level event queue. This not only speeds up delivery of the event but also avoids situations in which an Apple event sent in response to a user action arrives in the event queue after some other event that really occurred later than the user action. For example, suppose a user chooses Cut from the Edit menu and then clicks in another window. If the Cut event arrives in the queue after the window activate event, a selection in the wrong window might be cut.
Your application can send events to itself using other forms of addressing, such as the true process serial number returned by GetCurrentProcess. Because direct dispatching avoids event sequence problems, applications should generally send events to themselves by using an address descriptor record of descriptor type typeProcessSerialNumber with the kCurrentProcess constant rather than using a true process serial number or an application signature.
IMPORTANT
When Apple event recording has been turned on, the Apple Event Manager records every event that your application sends to itself unless you specify the kAEDontRecord flag in the sendMode parameter of the AESend function.s
Sending an Apple Event
To send an Apple event, you first create an Apple event, add parameters and attributes to it, and then use the AESend function to send it.
When you send an Apple event, you specify various options to indicate how the server should handle the Apple event. You request a user interaction level from the server and specify whether the server can switch directly to the foreground if user interaction is needed, whether your application is willing to wait for a reply Apple event, whether reconnection is allowed, and whether your application wants a return receipt for the Apple event.
You specify these options by setting flags in the sendMode parameter for AESend. Here are the constants that represent these flags:
kAEDontRecord = $00001000; {don’t record this event}
kAEDontExecute = $00002000; {don’t execute this event}
If you want your application to receive a reply Apple event, specify the kAEQueueReply or kAEWaitReply flag. If you want your application to receive the reply Apple event in its event queue, use kAEQueueReply. If you want your application to receive the reply Apple event in the reply parameter for AESend and you are willing to give up the processor while it is waiting for the reply, use kAEWaitReply. If you don’t want your application to receive a reply Apple event and your application doesn’t need to wait for the server to handle the Apple event, specify kAENoReply.
Note
Note
Before the Apple Event Manager sends a reply event back to the client application, the keyAddressAttr attribute contains the address of the client application. After the client receives the reply event, the keyAddressAttr attribute contains the address of the server application.u
If you specify kAENoReply or kAEQueueReply, the AESend function returns immediately after using the Event Manager to send the event. In this case, a noErr result code from AESend indicates that the Event Manager sent the Apple event; it does not mean that the server accepted or handled the Apple event.
When AESend returns, the reply parameter does not contain valid data if your application specifies kAENoReply or kAEQueueReply. The kAENoReply flag indicates that the Apple Event Manager will not return the reply Apple event to your application. The kAEQueueReply flag indicates that you want your application to receive the reply via its event queue rather than the reply parameter of AESend. If you specify kAEQueueReply, you must install a handler for the reply Apple event (event class kCoreEventClass and event ID kAEAnswer).
If you specify kAEWaitReply, the Apple Event Manager uses the Event Manager to send the event. The Apple Event Manager then calls the WaitNextEvent function on behalf of your application, causing your application to yield the processor and giving the server application a chance to receive and handle the Apple event. Your application continues to yield the processor until the server handles the Apple event or the request times out.
If you specify kAEWaitReply, you must provide an idle function. This function should process any update events, null events, operating-system events, or activate events that occur while your application is waiting for a reply. See “Writing an Idle Function,” which begins on page 5-21, for sample code that shows an idle function.
You use one of the three flags—kAENeverInteract, kAECanInteract, and kAEAlwaysInteract—to specify whether the server should interact with the user when handling the Apple event. Specify kAENeverInteract if the server should not interact with the user when handling the Apple event. You might specify this constant if you don’t want the user to be interrupted while the server is handling the Apple event.
Use the kAECanInteract flag if the server should interact with the user when the user needs to supply information to the server. Use the kAEAlwaysInteract flag if the server should interact with the user whenever the server normally asks a user to confirm a decision or interact in any other way, even if no additional information is needed from the user. Note that it is the responsibility of the server and client applications to agree on how to interpret the kAEAlwaysInteract flag.
If the client application does not set any one of the user interaction flags, the Apple Event Manager sets a default, depending on the location of the target of the Apple event. If the server application is on a remote computer, the Apple Event Manager sets the kAENeverInteract flag as the default. If the target of the Apple event is on the local computer, the Apple Event Manager sets the kAECanInteract flag as the default.
The server application should call AEInteractWithUser if it needs to interact with the user. If both the client and the server allow user interaction, the Apple Event Manager attempts to bring the server to the foreground if it is not already the foreground process. If both the kAECanSwitchLayer and the kAEWaitReply flags are set, and if the client application is the active application on the local computer, the Apple Event Manager brings the server application directly to the front. Otherwise, the Apple Event Manager posts a notification request asking the user to bring the server application to the front, regardless of whether the kAECanSwitchLayer flag is set. This ensures that the user will not be interrupted by an unexpected application switch.
You should specify the kAECanSwitchLayer flag only when the client and server applications reside on the same computer. In general, you should not set this flag if it would be confusing or inconvenient to the user for the server application to come to the front unexpectedly. This flag is ignored if you are sending an Apple event to a remote computer.
Specify the kAEDontReconnect flag if the Apple Event Manager should not reconnect if it receives a session closed error from the PPC Toolbox. If you don’t set this flag, the Apple Event Manager automatically attempts to reconnect and reestablish the session.
Specify the kAEWantReceipt flag if your application wants notification that the server application has accepted the Apple event. If you specify this flag, your application receives a return receipt as a high-level event.
If you specify the kAEWantReceipt flag and the server application does not accept the Apple event within the time specified by the timeOutInTicks parameter to AESend, the AESend function returns a timeout error. Note that AESend also returns a timeout error if your application sets the kAEWaitReply flag and does not receive the reply Apple event within the time specified by the timeOutInTicks parameter.
Specify the kAEDontRecord flag if your application is sending an Apple event to itself that you don’t want to be recorded. When Apple event recording has been turned on, every event that your application sends to itself will be automatically recorded by the Apple Event Manager except those sent with the kAEDontRecord flag set.
Specify the kAEDontExecute flag if your application is sending an Apple event to itself for recording purposes only—that is, if you want the Apple Event Manager to send a copy of the event to the recording process but you do not want your application actually to receive the event. (For more information about when to use the kAEDontExecute flag, see the chapter “Recording Apple Events” in this book.)
Listing 5-4 illustrates how to send a Multiply event (an imaginary Apple event for multiplying two long integers). It first creates an Apple event, adds parameters containing the numbers to multiply, then sends it, specifying various options. It also illustrates how to handle the reply Apple event that contains the result.
Note
Note
If you want to send Apple events, your application must set flags in its 'SIZE' resource indicating that it can handle high-level events, and it must provide handlers for the required Apple events. See “Accepting an Apple Event” on page 4-5 for information on setting the appropriate flags in the 'SIZE' resource and “Handling the Required Apple Events” on page 4-11 for information on supporting the required Apple events.u
Listing 5-4 Sending an Apple event
FUNCTION MySendMultiplyEvent (serverAddress: AEAddressDesc;
firstOperand: LongInt; secondOperand: LongInt;
VAR replyResultLongInt: LongInt): OSErr;
CONST
kArithmeticClass = 'ARTH'; {event class for arithmetic }
{ Apple events}
kMultiplyEventID = 'MULT'; {event ID for Multiply event}
keyMultOperand1 = 'OPN1'; {keyword for first parameter}
keyMultOperand2 = 'OPN2'; {keyword for second parameter}
{the Apple event wasn't successfully dispatched, }
{ the request timed out, the user canceled, or other error}
END;
ignoreErr := AEDisposeDesc(theAppleEvent);
MySendMultiplyEvent := myErr;
END;
The code in Listing 5-4 first creates an Apple event with kArithmeticClass as the event class and kMultiplyEventID as the event ID. It also specifies the server of the Apple event. See “Specifying a Target Address” on page 5-10 for information on specifying a target address and “Creating an Apple Event,” which begins on page 5-3, for more information on creating an Apple event.
The Multiply event shown in Listing 5-4 contains two parameters, each specifying a number to multiply. See “Adding Parameters to an Apple Event” on page 5-5 for examples of how to specify the parameters for the AEPutParamPtr function.
After adding the parameters to the event, the code uses AESend to send the event. The first parameter to AESend specifies the Apple event to send—in this example, the Multiply event. The next parameter specifies the reply Apple event.
This example specifies kAEWaitReply in the third parameter, indicating that the client is willing to yield the processor for the specified timeout value (120 ticks, or 2 seconds). The kAENeverInteract flag indicates that the server should not interact with the user when processing the Apple event. The fourth parameter specifies that the Multiply event is to be sent using normal priority (that is, placed at the end of the event queue). You can specify the kAEHighPriority flag to place the event in the front of the event queue, but this is not usually recommended.
The next to last parameter specifies the address of an idle function. If you specify kAEWaitReply, you must provide an idle function. This function should process any update events, null events, operating-system events, or activate events that occur while your application is waiting for a reply. See “Writing an Idle Function,” which begins on page 5-21, for sample code that shows an idle function.
The last parameter to AESend specifies a filter function. You can supply a filter function to filter high-level events that your application may receive while waiting for a reply Apple event. You can specify NIL for this parameter if you do not need to filter high-level events while waiting for a reply. See “Writing a Reply Filter Function” on page 5-24 for more information.
If you specify kAEWaitReply, a noErr result code from AESend indicates that the Apple event was sent successfully, not that the server has completed the requested action successfully. Therefore, you should find out whether a result code was returned from the handler by checking the reply Apple event for the existence of either the keyErrorNumber or keyErrorString parameter. If the keyErrorNumber parameter does not exist or contains the noErr result code, you can use AEGetParamPtr to get the parameter you’re interested in from the reply Apple event.
The MySendMultiplyEvent function in Listing 5-4 checks the function result of AESend. If it is noErr, MySendMultiplyEvent checks the keyErrorNumber parameter of the reply Apple event to determine whether the server successfully handled the Apple event. If this parameter exists and indicates that an error occurred, MySendMultiplyEvent gets the error string out of the keyErrorString parameter. Otherwise, the server performed the request, and the reply Apple event contains the answer to the multiplication request.
When you have finished using the Apple event specified in the AESend function and no longer need the reply Apple event, you must dispose of both the original event and the reply by calling the AEDisposeDesc function.
IMPORTANT
If your application sends Apple events to itself using a typeProcessSerialNumber address descriptor record with the lowLongOfPSN field set to kCurrentProcess, the Apple Event Manager jumps directly to the appropriate Apple event handler without going through the normal event-processing sequence. For this reason, your application will not appear to run more slowly when it sends Apple events to itself. For more information, see “Addressing an Apple Event for Direct Dispatching” on page 5-13.s
Dealing With Timeouts
When your application calls AESend and chooses to wait for the server application to handle the Apple event, it can also specify the maximum amount of time it is willing to wait for a response. You can specify a timeout value in the timeOutInTicks parameter to AESend. You can either specify a particular length of time, in ticks, that your application is willing to wait, or you can specify the kNoTimeOut constant or the kAEDefaultTimeout constant.
Use the kNoTimeOut constant to indicate that your application is willing to wait forever for a response from the server. You should use this value only if you are sure that the server will respond in a reasonable amount of time. You should also implement a method of checking whether the user wants to cancel. The idle function that you specify as a parameter to AESend should check the event queue for any instances of Command-period and immediately return TRUE as its function result if it finds a request to cancel in the event queue.
Use the kAEDefaultTimeout constant if you want the Apple Event Manager to use a default timeout value. The Apple Event Manager uses a timeout value of about one minute if you specify this constant.
If you set the kAEWaitReply flag and the server doesn’t have a handler for the Apple event, the server immediately returns the errAEEventNotHandled result code. If the server doesn’t respond within the length of time specified by the timeout value, AESend returns the errAETimeout result code and a reply Apple event that contains no data. This result code does not necessarily mean that the server failed to perform the requested action; it means only that the server did not complete processing within the specified time. The server might still be processing the Apple event, and it might still send a reply.
If the server finishes processing the Apple event sometime after the time specified in the keyTimeoutAttr attribute has expired, it returns a reply Apple event to AEProcessAppleEvent. The Apple Event Manager then adds the actual data to the reply. Thus, your application can continue to check the reply Apple event to see if the server has responded, even after the time expires. If the server has not yet sent the reply when the client attempts to extract data from the reply Apple event, the Apple Event Manager functions return the errAEReplyNotArrived result code. After the reply Apple event returns from the server, the client can extract the data in the reply.
Additionally, the server can examine the keyTimeoutAttr attribute of the Apple event to determine the timeout value specified by the client. You can use the value of this attribute as a rough estimate of how much time your handler has to respond. You can assume that your handler has less time to respond than the timeout value, because transmitting the Apple event uses some of the available time, as does transmitting the reply Apple event back to the client, and the event may have been in the queue for a while already.
If you set the kAENoReply or kAEQueueReply flag, the Apple Event Manager ignores any timeout value you specify, because your application is not waiting for the reply. An attempt by the server to examine the keyTimeoutAttr attribute in this situation generates the error errAEDescNotFound.
If your handler needs more time than is specified in the keyTimeoutAttr attribute, you can reset the timer by using the AEResetTimer function. This function resets the timeout value of an Apple event to its starting value.
Writing an Idle Function
This section describes how to write an idle function for use with the AESend or AEInteractWithUser function.
When your application sends an Apple event, you can set one of three flags in the sendMode parameter to AESend that specify how you want to deal with the reply: kAENoReply if you don’t want your application to receive a reply, kAEQueueReply if you want it to receive the reply in its event queue, or kAEWaitReply if you want the reply returned in the reply parameter of AESend and you are willing to give up the processor while your application is waiting for the reply.
If you specify kAENoReply or kAEQueueReply, the AESend function returns immediately after using the Event Manager to send the event. If you specify kAEWaitReply, the AESend function does not return until either the server application finishes handling the Apple event or a specified amount of time expires. In this case the AESend function calls WaitNextEvent on behalf of your application. This yields the processor to other processes, so that the server has an opportunity to receive and process the Apple event sent by your application. While your application is waiting for a reply, it cannot receive events unless it provides an idle function.
If you provide a pointer to an idle function as a parameter to the AESend function, AESend calls your idle function whenever an update event, null event, operating-system event, or activate event is received for your application. To allow your application to process high-level events that it receives while waiting for a reply, provide a reply filter function. See the next section, “Writing a Reply Filter Function,” for more information.
Your application can yield the processor in a similar manner when it calls the AEInteractWithUser function. If AEInteractWithUser needs to post a notification request to bring your application to the front, your application yields the processor until the user brings your application to the front. To receive events while waiting for the user to bring your application to the front, you must provide an idle function.
If you provide a pointer to an idle function as a parameter to the AEInteractWithUser function, AEInteractWithUser calls your idle function whenever an update event, null event, operating-system event, or activate event is received for your application.
An idle function must use this syntax:
FUNCTION MyIdleFunction (VAR event: EventRecord;
VAR sleepTime: LongInt;
VAR mouseRgn: RgnHandle): Boolean;
The event parameter is the event record of the event to process. The sleepTime parameter and mouseRgn parameter are values that your idle function sets the first time it is called; thereafter they contain the values your function set. Your idle function should return a Boolean value that indicates whether your application wishes to continue waiting. Set the function result to TRUE if your application is no longer willing to wait for a reply from the server or for the user to bring the application to the front. Set the function result to FALSE if your application is still willing to wait.
You use the sleepTime and mouseRgn parameters in the same way as the sleep and mouseRgn parameters of the WaitNextEvent function. Specify in the sleepTime parameter the amount of time (in ticks) during which your application agrees to relinquish the processor if no events are pending for it.
In the mouseRgn parameter, you specify a screen region that determines the conditions under which your application is to receive notice of mouse-moved events. Your idle function receives mouse-moved events only if your application is the front application and the cursor strays outside the region you specify.
Your idle function receives only update events, null events, operating-system events, and activate events. When your idle function receives a null event, it can use the idle time to update a status dialog box, animate cursors, or perform similar tasks. If your idle function receives any of the other events, it should handle the event as it normally would if received in its event loop.
Listing 5-5 shows an example of an idle function for use with AESend or AEInteractWithUser. The idle function processes update events, null events, operating-system events, and activate events. The first time the function is called it receives a null event. At this time, it sets the sleepTime and mouseRgn parameters. The function continues to process events until the server finishes handling the Apple event or the user brings the application to the front.
Your application should implement a method of checking whether the user wants to cancel. The MyCancelInQueue function in Listing 5-5 checks the event queue for any instances of Command-period and immediately returns TRUE as its function result if it finds a request to cancel in the event queue.
Listing 5-5 An idle function
FUNCTION MyIdleFunction (VAR event: EventRecord;
VAR sleeptime: LongInt;
VAR mouseRgn: RgnHandle): Boolean;
BEGIN
MyIdleFunction := FALSE;
{the MyCancelInQueue function checks for Command-period}
IF MyCancelInQueue THEN
BEGIN
MyIdleFunction := TRUE;
Exit(MyIdleFunction);
END;
CASE event.what OF
updateEvt,
activateEvt, {every idle function should handle }
osEvt: { these kinds of events}
BEGIN
MyAdjustCursor(event.where, gCursorRgn);
DoEvent(event);
END;
nullEvent:
BEGIN
{set the sleepTime and mouseRgn parameters}
mouseRgn := gCursorRgn;
sleeptime := 10; {use the correct value for your }
{ app}
DoIdle; {the application's idle handling}
END;
END; {of CASE}
END;
Writing a Reply Filter Function
If your application calls AESend and chooses to yield the processor to other processes while waiting for a reply, you can provide an idle function to process update, null, operating-system, and activate events, and you can provide a reply filter function to process high-level events. The previous section describes how an idle function processes events.
Your reply filter function can process any high-level events that it is willing to handle while waiting for a reply Apple event. For example, your application can choose to handle Apple events from other processes while waiting. Note, however, that your application must maintain any necessary state information. Your reply filter function must not accept any Apple events that can change the state of your application and make it impossible to return to its previous state.
A reply filter function must use this syntax:
FUNCTION MyReplyFilter (VAR event: EventRecord;
returnID: LongInt;
transactionID: LongInt;
sender: AEAddressDesc): Boolean;
The event parameter is the event record for a high-level event. The next three parameters contain valid information only if the event is an Apple event. The returnID parameter is the return ID for the Apple event. The transactionID parameter is the transaction ID for the Apple event. The sender parameter contains the address of the application or process that sent the Apple event.
Your reply filter function should return TRUE as the function result if you want to accept the Apple event; otherwise, it should return FALSE. If your filter function returns TRUE, the Apple Event Manager calls the AEProcessAppleEvent function on behalf of your application, and your handler routine is called to process the Apple event. In this case, make sure your handler is not called while it is still being used by an earlier call.
Reference to Creating and Sending Apple Events
This section describes the basic Apple Event Manager routines that your application can use to create and send Apple events. It also describes application-defined idle functions and reply filter functions that your application can provide for use by the Apple Event Manager.
For information about data structures used with the routines described in this chapter, see the section “Data Structures Used by the Apple Event Manager,” which begins on page 4-56.
Routines for Creating and Sending Apple Events
This section describes the Apple Event Manager routines you can use to create Apple events, create and duplicate descriptor records, create and add items to descriptor lists and AE records, add parameters and attributes to Apple events, and send Apple events. The section “Routines for Responding to Apple Events,” which begins on page 4-61, describes other Apple Event Manager routines used for both responding to and creating Apple events.
Creating Apple Events
The AECreateAppleEvent function allows you to create an Apple event.
AECreateAppleEvent
You can use the AECreateAppleEvent function to create an Apple event with several important attributes but no parameters. You add parameters to the Apple event after you create it.
FUNCTION AECreateAppleEvent (theAEEventClass: AEEventClass;
theAEEventID: AEEventID;
target: AEAddressDesc;
returnID: Integer;
transactionID: LongInt;
VAR result: AppleEvent): OSErr;
theAEEventClass
The event class of the Apple event to be created.
theAEEventID
The event ID of the Apple event to be created.
target The address of the server application.
returnID The return ID for the Apple event; if you specify kAutoGenerateReturnID, the Apple Event Manager assigns a return ID that is unique to the current session.
transactionID
The transaction ID for this Apple event. A transaction is a sequence of Apple events that are sent back and forth between the client and server applications, beginning with the client’s initial request for a service. All Apple events that are part of a transaction must have the same transaction ID.
result The AECreateAppleEvent function returns, in this parameter, the Apple event that it creates.
DESCRIPTION
The AECreateAppleEvent function creates an Apple event.Your application is responsible for using the AEDisposeDesc function to dispose of the Apple event when you no longer need it.
If AECreateAppleEvent returns a nonzero result code, it returns a null descriptor record unless the Apple Event Manager is not available because of limited memory.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
SEE ALSO
See “Creating an Apple Event,” which begins on page 5-3, for more information on how to create an Apple event.
See “Specifying a Target Address” on page 5-10 for information on how to address an Apple event.
Creating and Duplicating Descriptor Records
The AECreateDesc function converts data into a descriptor record, and the AEDuplicateDesc function makes a copy of a descriptor record.
AECreateDesc
You can use the AECreateDesc function to convert data into a descriptor record.
FUNCTION AECreateDesc (typeCode: DescType; dataPtr: Ptr;
dataSize: Size; VAR result: AEDesc): OSErr;
typeCode The descriptor type for the descriptor record.
dataPtr A pointer to the data for the descriptor record.
dataSize The length, in bytes, of the data for the descriptor record.
result The descriptor record that the AECreateDesc function creates.
DESCRIPTION
The AECreateDesc function creates a new descriptor record that incorporates the specified data. Your application is responsible for using the AEDisposeDesc function to dispose of the resulting descriptor record when you no longer need it. You normally do this after receiving a result code from the AESend function.
If AECreateDesc returns a nonzero result code, it returns a null descriptor record unless the Apple Event Manager is not available because of limited memory.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
SEE ALSO
For examples of the use of AECreateDesc, see “Adding Parameters to an Apple Event,” which begins on page 5-5, and Listing 5-2 on page 5-11.
AEDuplicateDesc
You can use the AEDuplicateDesc function to make a copy of a descriptor record.
FUNCTION AEDuplicateDesc (theAEDesc: AEDesc;
VAR result: AEDesc): OSErr;
theAEDesc The descriptor record to be duplicated.
result The duplicate descriptor record.
DESCRIPTION
The AEDuplicateDesc function creates a new descriptor record by copying the descriptor record from the parameter theAEDesc. Your application is responsible for using the AEDisposeDesc function to dispose of the resulting descriptor record when you no longer need it. You normally do this after receiving a result code from the AESend function.
If AEDuplicateDesc returns a nonzero result code, it returns a null descriptor record unless the Apple Event Manager is not available because of limited memory.
It is common for applications to send Apple events that have one or more attributes or parameters in common. For example, if you send a series of Apple events to the same application, the address attribute is the same. In these cases, the most efficient way to create the necessary Apple events is to make a template Apple event that you can then copy—by calling the AEDuplicateDesc function—as needed. You then fill in or change the remaining parameters and attributes of the copy, send the copy by calling AESend, and dispose of the copy—by calling AEDisposeDesc—after AESend returns a result code.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
Creating Descriptor Lists and AE Records
The AECreateList function allows you to create an empty descriptor list or AE record.
AECreateList
You can use the AECreateList function to create an empty descriptor list or AE record.
FUNCTION AECreateList (factoringPtr: Ptr; factoredSize: Size;
isRecord: Boolean;
VAR resultList: AEDescList): OSErr;
factoringPtr
A pointer to the data at the beginning of each descriptor that is the same for all descriptor records in the list. If there is no common data, or if you decide not to isolate the common data, specify NIL as the value of this parameter.
factoredSize
The size of the common data. If there is no common data, or if you decide not to isolate the common data, the value of factoredSize must be 0. (See the description that follows for more information.)
isRecord A Boolean value that specifies the kind of list to create. If you set it to TRUE, the Apple Event Manager creates an AE record. If you set it to FALSE, the Apple Event Manager creates a descriptor list.
resultList
The descriptor list or AE record that the AECreateList function creates.
DESCRIPTION
The AECreateList function creates an empty descriptor list or AE record. Your application is responsible for using the AEDisposeDesc function to dispose of the resulting descriptor record when you no longer need it. You normally do this after receiving a result code from the AESend function.
If you intend to use a descriptor list for a factored Apple event array, you must provide, in the factoringPtr parameter, a pointer to the data shared by all items in the array and, in the factoredSize parameter, the size of the common data. The common data must be 4, 8, or more than 8 bytes in length because it always consists of (a) the descriptor type (4 bytes); (b) the descriptor type (4 bytes) and the size of each item’s data (4 bytes); or (c) the descriptor type (4 bytes), the size of each item’s data (4 bytes), and some portion of the data itself (1 or more bytes).
If AECreateList returns a nonzero result code, it returns a null descriptor record unless the Apple Event Manager is not available because of limited memory.
RESULT CODESnoErr 0 No error
paramErr –50 Parameter error (value of handler pointer is NIL or odd)
memFullErr –108 Not enough room in heap zone
SEE ALSO
For an example of the use of AECreateList, see Listing 5-1 on page 5-9.
For information about data types used with Apple event arrays, see “Apple Event Array Data Types” on page 4-60.
Adding Items to Descriptor Lists
The Apple Event Manager provides three routines that allow you to add descriptor records to any descriptor list, including an Apple event record. The AEPutPtr function converts data specified in a buffer to a descriptor record and adds the descriptor record to a descriptor list. The AEPutDesc function adds a descriptor record to a descriptor list. The AEPutArray function puts the data for an Apple event array into a descriptor list.
AEPutPtr
You can use the AEPutPtr routine to add data specified in a buffer to any descriptor list as a descriptor record.
FUNCTION AEPutPtr (theAEDescList: AEDescList; index: LongInt;
typeCode: DescType; dataPtr: Ptr;
dataSize: Size): OSErr;
theAEDescList
The descriptor list to which to add a descriptor record.
index The position of the descriptor record in the descriptor list. (For example, the value 2 specifies the second descriptor record in the list.) If there is already a descriptor record in the specified position, it is replaced. If the value of index is 0, the descriptor record is added to the end of the list.
typeCode The descriptor type for the resulting descriptor record.
dataPtr A pointer to the data for the descriptor record.
dataSize The length, in bytes, of the data for the descriptor record.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
errAEIllegalIndex –1719 Not a valid list index
SEE ALSO
For an example of the use of AEPutPtr, see Listing 5-1 on page 5-9.
AEPutDesc
You can use the AEPutDesc function to add a descriptor record to any descriptor list.
FUNCTION AEPutDesc (theAEDescList: AEDescList; index: LongInt;
theAEDesc: AEDesc): OSErr;
theAEDescList
The descriptor list to which to add a descriptor record.
index The position of the descriptor record in the descriptor list. (For example, the value 2 specifies the second descriptor record in the list.) If there is already a descriptor record in the specified position, it is replaced. If the value of index is 0, the descriptor record is added to the end of the list.
theAEDesc The descriptor record to be added to the list.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
errAEIllegalIndex –1719 Not a valid list index
AEPutArray
You can use the AEPutArray function to put the data for an Apple event array into any descriptor list.
FUNCTION AEPutArray (theAEDescList: AEDescList;
arrayType: AEArrayType;
arrayPtr: AEArrayDataPointer;
itemType: DescType;
itemSize: Size; itemCount: LongInt): OSErr;
theAEDescList
The descriptor list into which to put the Apple event array. If there are any items already in the descriptor list, they are replaced.
arrayType The Apple event array type to be created. This is specified by one of the following constants: kAEDataArray, kAEPackedArray, kAEHandleArray, kAEDescArray, or kAEKeyDescArray.
arrayPtr A pointer to the buffer containing the array.
itemType For arrays of type kAEDataArray, kAEPackedArray, or kAEHandleArray, the descriptor type of array items to be created.
itemSize For arrays of type kAEDataArray or kAEPackedArray, the size (in bytes) of the array items to be created.
itemCount The number of elements in the array.
DESCRIPTION
When you use AEPutArray to put an array into a factored descriptor list, each array item must include the data that is common to all the descriptor records in the list. The Apple Event Manager automatically isolates the data you specified in the call to AECreateList that is common to all the elements of the array.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
SEE ALSO
For information about data types and constants used with AEPutArray, see “Apple Event Array Data Types” on page 4-60.
For more information about creating descriptor lists for Apple event arrays, see the description of AECreateList on page 5-28.
Adding Data and Descriptor Records to AE Records
The Apple Event Manager provides two routines that allow you to add data and descriptor records to AE records. The AEPutKeyPtr function takes a pointer to data, a descriptor type, and a keyword and converts them into a keyword-specified descriptor record that it adds to an AE record. The AEPutKeyDesc function takes a descriptor record and a keyword and converts them into a keyword-specified descriptor record that it adds to an AE record.
AEPutKeyPtr
You can use the AEPutKeyPtr function to add a pointer to data, a descriptor type, and a keyword to an AE record as a keyword-specified descriptor record.
FUNCTION AEPutKeyPtr (theAERecord: AERecord;
theAEKeyword: AEKeyword;
typeCode: DescType; dataPtr: Ptr;
dataSize: Size): OSErr;
theAERecord
The AE record to which to add a keyword-specified
descriptor record.
theAEKeyword
The keyword that identifies the descriptor record. If the AE record already includes a descriptor record with this keyword, it is replaced.
typeCode The descriptor type for the keyword-specified descriptor record.
dataPtr A pointer to the data for the keyword-specified descriptor record.
dataSize The length, in bytes, of the data for the keyword-specified descriptor record.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
AEPutKeyDesc
You can use the AEPutKeyDesc function to add a descriptor record and a keyword to an AE record as a keyword-specified descriptor record.
FUNCTION AEPutKeyDesc (theAERecord: AERecord;
theAEKeyword: AEKeyword;
theAEDesc: AEDesc): OSErr;
theAERecord
The AE record to which to add the keyword-specified descriptor record.
theAEKeyword
The keyword specifying the descriptor record. If there was already a keyword-specified descriptor record with this keyword, it is replaced.
theAEDesc The descriptor record for the keyword-specified descriptor record.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
Adding Parameters and Attributes to Apple Events
The Apple Event Manager provides four functions that allow you to add Apple event parameters and attributes to an Apple event. The AEPutParamPtr and AEPutParamDesc functions add parameters to a specified Apple event. The AEPutAttributePtr and AEPutAttributeDesc functions add attributes to a specified Apple event.
AEPutParamPtr
You can use the AEPutParamPtr function to add a pointer to data, a descriptor type, and a keyword to an Apple event as an Apple event parameter.
FUNCTION AEPutParamPtr (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
typeCode: DescType; dataPtr: Ptr;
dataSize: Size): OSErr;
theAppleEvent
The Apple event to which to add a parameter.
theAEKeyword
The keyword for the parameter to be added. If the Apple event already included a parameter with this keyword, the parameter is replaced.
typeCode The descriptor type for the parameter.
dataPtr A pointer to the data for the parameter.
dataSize The length, in bytes, of the data for the parameter.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
SEE ALSO
For an example of the use of AEPutParamPtr, see “Adding Parameters to an Apple Event,” which begins on page 5-5.
AEPutParamDesc
You can use the AEPutParamDesc function to add a descriptor record and a keyword to an Apple event as an Apple event parameter.
FUNCTION AEPutParamDesc (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
theAEDesc: AEDesc): OSErr;
theAppleEvent
The Apple event to which to add a parameter.
theAEKeyword
The keyword for the parameter to be added. If the Apple event already included a parameter with this keyword, the parameter is replaced.
theAEDesc The descriptor record for the parameter.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
SEE ALSO
For an example of the use of AEPutParamDesc, see “Adding Parameters to an Apple Event,” which begins on page 5-5.
AEPutAttributePtr
You can use the AEPutAttributePtr function to add a pointer to data, a descriptor type, and a keyword to an Apple event as an attribute.
FUNCTION AEPutAttributePtr (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
typeCode: DescType;
dataPtr: Ptr; dataSize: Size): OSErr;
theAppleEvent
The Apple event to which to add an attribute.
theAEKeyword
The keyword for the attribute to be added.
TYPE AEKeyword = PACKED ARRAY[1..4] OF Char;
The keyword can be any of the constants listed in the description that follows. If the Apple event already included an attribute with this keyword, the attribute is replaced.
typeCode The descriptor type for the attribute.
dataPtr A pointer to the buffer containing the data to be assigned to the attribute.
dataSize The length, in bytes, of the data to be assigned to the attribute.
DESCRIPTION
The AEPutAttributePtr function adds the specified pointer to data, descriptor type, and keyword to the specified Apple event as an attribute. You can specify the parameter theAEKeyWord using any of the following constants:
CONST
keyAddressAttr = 'addr'; {address of target }
{ application}
keyEventClassAttr = 'evcl'; {event class}
keyEventIDAttr = 'evid'; {event ID}
keyEventSourceAttr = 'esrc'; {source application}
keyInteractLevelAttr = 'inte'; {settings to allow the }
keyOptionalKeywordAttr = 'optk'; {list of optional }
{ parameters for Apple }
{ event}
keyOriginalAddressAttr = 'from'; {address of original source }
{ of Apple event}
keyReturnIDAttr = 'rtid'; {return ID for reply Apple }
{ event}
keyTimeoutAttr = 'timo'; {length of time in ticks }
{ that client will wait }
{ for reply or result from }
{ the server}
keyTransactionIDAttr = 'tran'; {transaction ID identifying }
{ a series of Apple events}
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
AEPutAttributeDesc
You can use the AEPutAttributeDesc function to add a descriptor record and a keyword to an Apple event as an attribute.
FUNCTION AEPutAttributeDesc (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
theAEDesc: AEDesc): OSErr;
theAppleEvent
The Apple event to which you are adding an attribute.
theAEKeyword
The keyword for the attribute to be added.
TYPE AEKeyword = PACKED ARRAY[1..4] OF Char;
The keyword can be any of the constants listed in the description of AEPutAttributePtr on page 5-35. If the Apple event already included an attribute with this keyword, the attribute is replaced.
theAEDesc The descriptor record to be assigned to the attribute. The descriptor type of the specified descriptor record should match the defined descriptor type for that attribute. For example, the keyEventSourceAttr attribute has the typeShortInteger descriptor type.
DESCRIPTION
The AEPutAttributeDesc function takes a descriptor record and a keyword and adds them to an Apple event as an attribute. If the descriptor type required for the attribute is different from the descriptor type of the descriptor record, the Apple Event Manager attempts to coerce the descriptor record into the required type, with one exception: the Apple Event Manager does not attempt to coerce the data for an address attribute, thereby allowing applications to use their own address types.
RESULT CODESnoErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
SEE ALSO
For an example of the use of AEPutAttributeDesc, see Listing 5-1 on page 5-9.
Sending Apple Events
The AESend function allows you to send an Apple event that you have previously created with the AECreateAppleEvent function.
AESend
You can use the AESend function to send an Apple event.
FUNCTION AESend (theAppleEvent: AppleEvent;
VAR reply: AppleEvent; sendMode: AESendMode;
sendPriority: AESendPriority;
timeOutInTicks: LongInt; idleProc: IdleProcPtr;
filterProc: EventFilterProcPtr): OSErr;
theAppleEvent
The Apple event to be sent.
reply The reply Apple event returned by the AESend function if you specify the kAEWaitReply flag in the sendMode parameter. (If you specify the kAEQueueReply flag in the sendMode parameter, you receive the reply Apple event in your event queue.) If you specify kAENoReply flag, the reply Apple event returned by this function is a null descriptor record. If you specify kAEWaitReply in the sendMode parameter, your application is responsible for using the AEDisposeDesc function to dispose of the descriptor record returned in the reply parameter.
sendMode Specifies the following: the reply mode for the Apple event (set with one of the constants kAENoReply, kAEQueueReply, or kAEWaitReply); the interaction level (set with one of the constants kAENeverInteract, kAECanInteract, or kAEAlwaysInteract, which represent flags in the keyInteractLevelAttr attribute); the application switch mode (set with the kAECanSwitchLayer constant); the reconnection mode (set with the kAEDontReconnect constant); and the return receipt mode (set with the kAEWantReceipt constant). You obtain the value for this parameter by adding the appropriate constants. (The description that follows provides more details about the sendMode flags.)
sendPriority
An integer of data type AESendPriority that specifies whether the Apple event is put at the back of the event queue (indicated by the kAENormalPriority flag) or at the front of the queue (indicated by the kAEHighPriority flag).
timeOutInTicks
If the reply mode specified in the sendMode parameter is kAEWaitReply, or if a return receipt is requested, this parameter specifies the length of time (in ticks) that the client application is willing to wait for the reply or return receipt from the server application before timing out. Most applications should use the kAEDefaultTimeout constant, which tells the Apple Event Manager to provide an appropriate timeout duration. If the value of this parameter is kNoTimeOut, the Apple event never times out.
idleProc A pointer to a function that handles events (such as update, operating-system, activate, and null events) that your application receives while waiting for a reply. Your application can also perform other tasks (such as displaying a wristwatch or spinning beachball cursor) while waiting for a reply or a return receipt. Your application must provide an idle function if it specifies the kAEWaitReply flag in the sendMode parameter.
filterProc
A pointer to a function that accepts certain incoming Apple events that are received while the handler waits for a reply or a return receipt and filters out the rest.
DESCRIPTION
You can use one of the following flags in the sendMode parameter to specify the reply mode for an Apple event. Only one of these flags may be set.
Flag Description
kAENoReply Your application does not want a reply Apple event; the server processes your Apple event as soon as it has the opportunity.
kAEQueueReply Your application wants a reply Apple event; the reply appears in your event queue as soon as the server has the opportunity to process and respond to your Apple event.
kAEWaitReply Your application wants a reply Apple event and is willing to give up the processor while waiting for the reply; for example, if the server application is on the same computer as your application, your application yields the processor to allow the server to respond to your Apple event. If you specify kAEWaitReply, you should provide an idle function.
You can communicate your user interaction preferences to the server application by specifying one of the following flags in the sendMode parameter. Only one of these flags may be set.
Flag Description
kAENeverInteract The server application should never interact with the user in response to the Apple event. If this flag is set, AEInteractWithUser returns the errAENoUserInteraction result code. This flag is the default when an Apple event is sent to a remote application.
kAECanInteract The server application can interact with the user in response to the Apple event—by convention, if the user needs to supply information to the server. If this flag is set and the server allows interaction, AEInteractWithUser either brings the server application to the foreground or posts a notification request. This flag is the default when an Apple event is sent to a local application.
kAEAlwaysInteract The server application can interact with the user in response to the Apple event—by convention, whenever the server application normally asks a user to confirm a decision or interact in any other way, even if no additional information is needed from the user. If this flag is set and the server allows interaction, AEInteractWithUser either brings the server application to the foreground or posts a notification request.
The flags in the following list specify the application switch mode, the reconnection mode, and the return receipt mode. Any of these flags may be set.
Flag Description
kAECanSwitchLayer If both the client and server allow interaction, and if the client application is the active application on the local computer and is waiting for a reply (that is, it has set the kAEWaitReply flag), AEInteractWithUser brings the server directly to the foreground. Otherwise, AEInteractWithUser uses the Notification Manager to request that the user bring the server application to the foreground.
kAEDontReconnect The Apple Event Manager must not automatically try to reconnect if it receives a sessClosedErr result code from the PPC Toolbox.
kAEWantReceipt The sender wants to receive a return receipt for this Apple event from the Event Manager. (A return receipt means only that the receiving application accepted the Apple event; the Apple event may or may not be handled successfully after it is accepted.) If the receiving application does not send a return receipt before the request times out, AESend returns errAETimeout as its function result.
If the Apple Event Manager cannot find a handler for an Apple event in either the application or system Apple event dispatch table, it returns the result code errAEEventNotHandled to the server application (as the result of the AEProcessAppleEvent function). If the client application is waiting for a reply, the Apple Event Manager also returns this result code to the client.
The AESend function returns noErr as its function result if the Apple event was successfully sent by the Event Manager. A noErr result from AESend does not indicate that the Apple event was handled successfully; it indicates only that the Apple event was successfully sent by the Event Manager. If the handler returns a result code other than noErr, and if the client is waiting for a reply, it is returned in the keyErrorNumber parameter of the reply Apple event.
If your application is sending an event to itself, you can set one of these flags to prevent the event from being recorded or to ask the Apple Event Manager to record the event without your application actually receiving it. Only one of these flags may be set.
Flag Description
kAEDontRecord Your application is sending an event to itself but does not want the event recorded. When Apple event recording is on, the Apple Event Manager records a copy of every event your application sends to itself except for those events for which this flag is set.
kAEDontExecute Your application is sending an Apple event to itself for recording purposes only—that is, you want the Apple Event Manager to send a copy of the event to the recording process but you do not want your application actually to receive the event.
RESULT CODESnoErr 0 No error
eLenErr –92 Buffer too big to send
memFullErr –108 Not enough room in heap zone
userCanceledErr –128 User canceled an operation
procNotFound –600 No eligible process with specified process serial number
connectionInvalid –609 Nonexistent signature or session ID
noPortErr –903 Client hasn’t set 'SIZE' resource to indicate awareness of high-level events
destPortErr –906 Server hasn’t set 'SIZE' resource to indicate awareness of high-level events, or else is not present
sessClosedErr –917 The kAEDontReconnect flag in the sendMode parameter was set and the server quit, then restarted
errAEEventNotHandled –1708 Event wasn’t handled by an Apple event handler
errAEUnknownSendMode –1710 Invalid sending mode was passed
errAEWaitCanceled –1711 User canceled out of wait loop for reply or receipt
errAETimeout –1712 Apple event timed out
errAEUnknownAddressType –1716 Unknown Apple event address type
SEE ALSO
For more information on sending Apple events, see “Sending an Apple Event,” which begins on page 5-13.
For information on writing an idle function, see “Writing an Idle Function,” which begins on page 5-21.
For information on writing a reply filter function, see “Writing a Reply Filter Function,” which begins on page 5-24.
For information on when to use the kAEDontExecute flag, see the chapter “Recording Apple Events” in this book.
Application-Defined Routines
If your application sends an Apple event using AESend and is waiting for a reply, or if it calls AEInteractWithUser, you can provide an idle function to handle update events, null events, operating-system events, and activate events. You can also provide a reply filter function that can handle any high-level events that you want your application to handle while it is waiting for a reply or for user interaction.
MyIdleFunction
An idle function has the following syntax:
FUNCTION MyIdleFunction (VAR event: EventRecord;
VAR sleepTime: LongInt;
VAR mouseRgn: RgnHandle): Boolean;
event The event record of the event to process.
sleepTime Amount of time (in ticks) during which your application agrees to relinquish the processor if no events are pending.
mouseRgn A screen region that determines the conditions under which your application is to receive notice of mouse-moved events.
DESCRIPTION
If your application provides a pointer to an idle function (MyIdleFunction) as a parameter to AESend or AEInteractWithUser, the Apple Event Manager will call the idle function to handle any update event, null event, operating-system event, or activate event received for your application while it is waiting for a reply.
Set the function result to TRUE if your application is no longer willing to wait for a reply from the server or for the user to bring the application to the front. Set the function result to FALSE if your application is still willing to wait.
SEE ALSO
For more information, see “Writing an Idle Function,” which begins on page 5-21.
MyReplyFilter
A reply filter function has the following syntax:
FUNCTION MyReplyFilter (VAR event: EventRecord;
returnID: LongInt;
transactionID: LongInt;
sender: AEAddressDesc): Boolean;
event The event record for a high-level event. The next three parameters contain valid information only if the event is an Apple event.
returnID Return ID for the Apple event.
transactionID
Transaction ID for the Apple event.
sender Address of process that sent the Apple event.
DESCRIPTION
If your application provides a pointer to a reply filter function as a parameter to the AESend function, the reply filter function can process any high-level events that it is willing to handle while your application is waiting for a reply.
Your reply filter function should return TRUE as the function result if you want to accept the Apple event; otherwise, it should return FALSE.
SEE ALSO
For more information, see “Writing a Reply Filter Function” on page 5-24.
Summary of Creating and Sending Apple Events
Pascal Summary
Constants
CONST
gestaltAppleEventsAttr = 'evnt'; {selector for Apple events}
gestaltAppleEventsPresent = 0; {if this bit is set, then Apple }
{ Event Manager is available}
{Apple event descriptor types}
typeBoolean = 'bool'; {1-byte Boolean value}
typeChar = 'TEXT'; {unterminated string}
typeSMInt = 'shor'; {16-bit integer}
typeInteger = 'long'; {32-bit integer}
typeSMFloat = 'sing'; {SANE single}
typeFloat = 'doub'; {SANE double}
typeLongInteger = 'long'; {32-bit integer}
typeShortInteger = 'shor'; {16-bit integer}
typeLongFloat = 'doub'; {SANE double}
typeShortFloat = 'sing'; {SANE single}
typeExtended = 'exte'; {SANE extended}
typeComp = 'comp'; {SANE comp}
typeMagnitude = 'magn'; {unsigned 32-bit integer}
typeAEList = 'list'; {list of descriptor records}
typeAERecord = 'reco'; {list of keyword-specified }
noPortErr –903 Client hasn’t set 'SIZE' resource to indicate awareness of high-level events
destPortErr –906 Server hasn’t set 'SIZE' resource to indicate awareness of high-level events, or else is not present
sessClosedErr –917 The kAEDontReconnect flag in the sendMode parameter was set, and the server quit and then restarted
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAECorruptData –1702 Data in an Apple event could not be read
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
errAENewerVersion –1706 Need a newer version of the Apple Event Manager
errAENotAppleEvent –1707 Event is not an Apple event
errAEEventNotHandled –1708 Event wasn’t handled by an Apple event handler
errAEReplyNotValid –1709 AEResetTimer was passed an invalid reply
errAEUnknownSendMode –1710 Invalid sending mode was passed
errAEWaitCanceled –1711 User canceled out of wait loop for reply or receipt
errAETimeout –1712 Apple event timed out
errAENoUserInteraction –1713 No user interaction allowed
errAENotASpecialFunction –1714 The keyword is not valid for a special function
errAEParamMissed –1715 Handler cannot understand a parameter the client considers required
errAEUnknownAddressType –1716 Unknown Apple event address type
errAEHandlerNotFound –1717 No handler found for an Apple event or a coercion, or no object callback function found
errAEReplyNotArrived –1718 Reply has not yet arrived
errAEIllegalIndex –1719 Not a valid list index
errAEImpossibleRange –1720 The range is not valid because it is impossible for a range to include the first and last objects that were specified; an example is a range in which the offset of the first object is greater than the offset of the last object
errAEWrongNumberArgs –1721 The number of operands provided for the kAENot logical operator is not 1
errAEAccessorNotFound –1723 There is no object accessor function for the specified object class and token descriptor type
errAENoSuchLogical –1725 The logical operator in a logical descriptor record is not kAEAnd, kAEOr, or kAENot
errAEBadTestKey –1726 The descriptor record in a test key is neither a comparison descriptor record nor a logical descriptor record
errAENotAnObjectSpec –1727 The objSpecifier parameter of AEResolve is not an object specifier record
errAENoSuchObject –1728 A run-time resolution error, for example: object specifier record asked for the third element, but there are only two
errAENegativeCount –1729 Object-counting function returned negative value
errAEEmptyListContainer –1730 The container for an Apple event object is specified by an empty list
errAEUnknownObjectType –1731 Descriptor type of token returned by AEResolve is not known to server application
errAERecordingIsAlreadyOn –1732 Attempt to turn recording on when it is already on
Listing 6-0
Table 6-0
Resolving and Creating Object Specifier Records
Contents
Resolving Object Specifier Records6-4
Descriptor Records Used in Object Specifier Records6-8
Object Class6-9
Container6-9
Key Form6-11
Key Data6-12
Key Data for a Property ID6-13
Key Data for an Object’s Name6-14
Key Data for a Unique ID6-14
Key Data for Absolute Position6-14
Key Data for Relative Position6-15
Key Data for a Test6-15
Key Data for a Range6-20
Installing Entries in the Object Accessor Dispatch Tables6-21
Installing Object Accessor Functions That Find Apple Event Objects6-23
Installing Object Accessor Functions That Find Properties6-27
Writing Object Accessor Functions6-28
Writing Object Accessor Functions That Find Apple Event Objects6-29
Writing Object Accessor Functions That Find Properties6-37
Defining Tokens6-39
Handling Whose Tests6-41
Writing Object Callback Functions6-45
Writing an Object-Counting Function6-48
Writing an Object-Comparison Function6-50
Writing Marking Callback Functions6-53
Creating Object Specifier Records6-55
Creating a Simple Object Specifier Record6-57
Specifying the Container Hierarchy6-61
Specifying a Property6-63
Specifying a Relative Position6-64
Creating a Complex Object Specifier Record6-64
Specifying a Test6-64
Specifying a Range6-72
Reference to Resolving and Creating Object Specifier Records6-75
Data Structures Used in Object Specifier Records6-75
Routines for Resolving and Creating Object Specifier Records6-77
Initializing the Object Support Library6-77
Setting Object Accessor Functions and Object Callback Functions6-77
Getting, Calling, and Removing Object Accessor Functions6-81
Resolving Object Specifier Records6-85
Deallocating Memory for Tokens6-87
Creating Object Specifier Records6-88
Application-Defined Routines6-94
Object Accessor Functions6-94
Object Callback Functions6-96
Summary of Resolving and Creating Object Specifier Records6-104
Pascal Summary6-104
Constants6-104
Data Types6-106
Routines for Resolving and Creating Object Specifier Records6-106
Application-Defined Routines6-108
C Summary6-109
Constants6-109
Data Types6-111
Routines for Resolving and Creating Object Specifier Records6-112
Application-Defined Routines6-114
Assembly-Language Summary6-115
Trap Macros6-115
Result Codes6-115
Resolving and Creating Object Specifier Records
This chapter describes how your application can use the Apple Event Manager and application-defined functions to resolve object specifier records. Your application must be able to resolve object specifier records to respond to core and functional-area Apple events defined in the Apple Event Registry: Standard Suites.
For example, after receiving a Get Data event that requests a table in a document, your application can use the Apple Event Manager and application-defined functions to parse the object specifier record in the direct parameter, locate the requested table, and send a reply Apple event containing the table’s data back to the application that requested it.
This chapter also describes how your application can use the Apple Event Manager to create object specifier records. If you want to factor your application for Apple event recording, or if you want to send Apple events directly to other applications, you need to know how to create object specifier records.
To use this chapter, you should be familiar with the chapters “Introduction to Apple Events” and “Responding to Apple Events” in this book. The section “Working With Object Specifier Records,” which begins on page 3-32, provides a general introduction to the subject.
If you plan to create object specifier records, you should also be familiar with the chapter “Creating and Sending Apple Events.” If you are factoring your application, you should read the chapter “Recording Apple Events” before you write code for resolving or creating object specifier records.
This chapter begins with an overview of the way your application works with the Apple Event Manager to resolve object specifier records. It then describes
n how the data in an object specifier record is organized
n how to install entries in the object accessor tables
n how to write object accessor and object callback functions
n how to create an object specifier record
IMPORTANT
Versions 1.0 and 1.01 of the Apple Event Manager do not include the routines for resolving and creating object specifier records described in this chapter. To use these routines with those versions of the Apple Event Manager, you must link the Object Support Library (OSL) with your application when you build it, and call the AEObjectInit function before calling any of the routines.s
Resolving Object Specifier Records
If an Apple event parameter consists of an object specifier record, your handler for the Apple event should resolve the object specifier record: that is, locate the Apple event objects it describes. The first step is to call the AEResolve function with the object specifier record as a parameter.
The AEResolve function performs tasks that are required to resolve any object specifier record, such as parsing its contents, keeping track of the results of tests, and handling memory management. When necessary, AEResolve calls application-defined functions to perform tasks that are unique to the application, such as locating a specific Apple event object in the application’s data structures or counting the number of Apple event objects in a container.
Note
Object specifier records are only valid while the Apple event that contains them is being handled. For example, if an application receives an Apple event asking it to cut row 5 of a table, what was row 6 then becomes row 5, and the original object specifier record that referred to row 5 no longer refers to the same row.u
The AEResolve function can call two kinds of application-defined functions. Object accessor functions locate Apple event objects. Object callback functions perform other tasks that only an application can perform, such as counting, comparing, or marking Apple event objects. This section provides an overview of the way AEResolve calls object accessor and object callback functions when it resolves object specifier records.
Each time AEResolve calls one of your application’s object accessor functions successfully, the object accessor function should return a special descriptor record created by your application, called a token, that identifies either an element in a specified container or a property of a specified Apple event object. The Apple Event Manager examines the token’s descriptor type but does nothing with the token’s data. When it needs to refer to the object the token identifies, the Apple Event Manager simply passes the token back to your application.
Each object accessor function provided by your application should either find elements of a given object class in a container identified by a token of a given descriptor type, or find properties of an Apple event object identified by a token of a specified descriptor type. The Apple Event Manager uses the object class ID and the descriptor type of the token that identifies the object’s container to determine which object accessor function to call.
It is up to you to decide how many object accessor functions you need to write for your application. You can write one object accessor function that locates Apple event objects of several different object classes, or you can write separate object accessor functions for certain object classes. Similarly, you may want to use only one descriptor type for all the tokens returned by your object accessor functions, or you may want to use several descriptor types. The way you define your tokens depends on the needs of your application.
You can use the AEInstallObjectAccessor function to create an object accessor dispatch table that the Apple Event Manager uses to map requests for Apple event objects to the appropriate object accessor function in your application. The Apple Event Manager uses the object class of each requested object and the descriptor type of the token that identifies the object’s container to determine which object accessor function to call. Depending on the container hierarchy for a given object specifier record and the way your application defines its object accessor functions, the Apple Event Manager may need to call a series of object accessor functions to resolve the nested object specifier records that describe an Apple event object’s container. For information about creating and using the object accessor dispatch table, see “Installing Entries in the Object Accessor Dispatch Tables,” which begins on page 6-21.
Figure 6-1 illustrates the major steps involved in resolving an object specifier record. The SurfWriter application shown in Figure 6-1 receives a Get Data event whose direct parameter is an object specifier record for a table named “Summary of Sales” in a document named “Sales Report.” The SurfWriter application’s handler for the Get Data event calls the AEResolve function with the object specifier record as a parameter. The AEResolve function begins to parse the object specifier record. The first object accessor function that AEResolve calls is usually the function that can identify the Apple event object in the application’s default container—the outermost container in the container hierarchy. In Figure 6-1, the object specifier record for the document “Sales Report” specifies the default container, so the Apple Event Manager calls the object accessor function in the SurfWriter application that can locate a document in a container identified by a descriptor record of descriptor type typeNull.
Figure 6-1 Resolving an object specifier record for a table in a document
After locating the document named “Sales Report,” the SurfWriter application returns a token to the Apple Event Manager—that is, a descriptor record that SurfWriter uses to identify the document. The Apple Event Manager examines the descriptor type of the token but does not need to know anything about the token’s data to continue parsing the object specifier record. Next, the Apple Event Manager calls the object accessor function that can identify a table in a container identified by a token of descriptor type typeMyDocToken. When the Apple Event Manager calls this object accessor function, it uses the token that describes the document to identify the table’s container. After the SurfWriter application has located the table named “Summary of Sales” in the document named “Sales Report,” it returns a token describing that table to the Apple Event Manager.
After your application has successfully located an Apple event object, the Apple Event Manager disposes of all previous tokens returned during resolution of the object specifier record for the object. The Apple Event Manager disposes of tokens by calling either the AEDisposeDesc function or your application’s token disposal function, if you have provided one, which is an object callback function that disposes of a token. In Figure 6-1, the AEResolve function calls the SurfWriter application’s token disposal function to dispose of the token for the document after AEResolve receives the token for the table. After the SurfWriter application has disposed of the token for the document, the AEResolve function returns the result of the resolution—that is, the token for the requested table—to the handler in the SurfWriter application that originally called AEResolve.
The Apple Event Manager can complete the cycle of parsing the object specifier record and calling the appropriate object accessor function to obtain a token as many times as necessary to identify every container in the container hierarchy and finish resolving an object specifier record, including disposing of the tokens for the containers. However, one token will always be left over—the token that identifies the requested Apple event object. After AEResolve returns this final token and your application performs the action requested by the Apple event, it is up to your application to dispose of the token. Your application can do so by calling the AEDisposeToken function, which in turn calls either AEDisposeDesc or your application’s token disposal function.
You need to provide a token disposal function only if a call to AEDisposeDesc is not sufficient by itself to dispose of a token or if you provide marking callback functions, which are three object callback functions that allow your application to use its own marking scheme rather than tokens when identifying large groups of Apple event objects. Your application is not required to provide marking callback functions.
To handle object specifier records that specify a test, your application must provide two object callback functions: (a) an object-counting function, which counts the number of elements of a given object class in a given container so that the Apple Event Manager can determine how many elements it must test to find the element or elements that meet a specified condition, and (b) an object-comparison function, which compares one element to another element or to a descriptor record and returns TRUE or FALSE.
Your application may also provide an error callback function that can identify which descriptor record caused the resolution of an object specifier record to fail. Your application is not required to provide an error callback function.
If your application resolves object specifier records without the help of the Apple Event Manager, it must extract the equivalent descriptor records and coerce them as necessary to get access to their data. The Apple Event Manager includes coercion handlers for these coercions; for information about this default coercion handling, see Table 4-1 on page 4-43.
For more information about object accessor functions, see “Writing Object Accessor Functions,” which begins on page 6-28. For more information about object callback functions, see “Writing Object Callback Functions,” which begins on page 6-45.
The next section, “Descriptor Records Used in Object Specifier Records,” describes how the data in an object specifier record is interpreted by the Apple Event Manager.
Descriptor Records Used in Object Specifier Records
An object specifier record is a coerced AE record of descriptor type typeObjectSpecifier. The data to which its data handle refers consists of four keyword-specified descriptor records:
Keyword Value Description of data
keyAEDesiredClass 'want' A four-character code for the object class
keyAEContainer 'from' An object specifier record (or in some cases a descriptor record with a handle whose value is NIL) that identifies the container for the requested objects
keyAEKeyForm 'form' A four-character code for the key form
keyAEKeyData 'seld' Data or nested descriptor records that specify a property, name, position, range, or test, depending on the key form
This section describes the descriptor types and data associated with each of these keywords. You need this information if your application resolves or creates object specifier records.
For a summary of the descriptor types and key forms discussed in this section, see
Table 6-11 on page 6-76. For an overview of object specifier records, see “Working With Object Specifier Records,” which begins on page 3-32.
Object Class
The object class of the requested objects is identified by an object class ID. The corresponding keyword-specified descriptor record takes this form:
Keyword Descriptor type Data
keyAEDesiredClass typeType Object class ID
The Apple Event Registry: Standard Suites defines constants for the standard object class IDs.
Container
The container for the requested objects is usually the object in which they are located. It can be identified in one of four ways:
typeNull Value of data handle is NIL. Specifies the default container at the top of the container hierarchy.
typeObjectBeingExamined Value of data handle is NIL. Specifies the container for elements that are tested one at a time; used only within key data for key form formTest.
typeCurrentContainer Value of data handle is NIL. Specifies a container for an element that demarcates one boundary in a range. Used only within key data for key form formRange.
The data that describes a container usually consists of another object specifier record. The ability to nest one object specifier record within another in this way makes it possible to identify a chain of containers that fully describes the location of one or more Apple event objects.
For example, Figure 6-2 shows nested object specifier records that specify the first row of a table named “Summary of Sales” in a document named “Sales Report.” The container specified by the object specifier record at the bottom of the figure describes the outermost container in the container hierarchy—the container for the document “Sales Report.”
Because a container must be specified for each Apple event object in a container hierarchy, a null descriptor record (that is, a descriptor record whose descriptor type is typeNull and whose data handle has the value NIL) is used to specify the application’s default container—the outermost container for any container hierarchy in that application.
Figure 6-2 Nested object specifier records that specify a container hierarchy
Note
The format used in Figure 6-2 and similar figures throughout this chapter does not show the structure of the nested object specifier records as they exist within an Apple event. Instead, these figures show what you would obtain after calling AEGetKeyDesc repeatedly to extract the object specifier records from an Apple event record.
When you call AEGetKeyDesc to extract a null descriptor record, the function returns a descriptor record of type AEDesc with a descriptor type of typeNull and a data handle whose value is 0.u
The object specifier data at the bottom of Figure 6-2 uses a null descriptor record to specify the document’s container—that is, the default container for the application. The object specifier record for the document identifies the document named “Sales Report”; the object specifier record for the table identifies the table named “Summary of Sales” in the document “Sales Report”; and the object specifier record for the row identifies the first row of the table named “Summary of Sales” in the document “Sales Report.”
An object specifier record in an Apple event parameter almost always includes nested object specifier records that specify the container hierarchy for the requested Apple event object. For the nested object specifier records shown in Figure 6-2, the relationship between each Apple event object and its container is always simple containment: it is located inside its container.
In other cases, the specified container may not actually contain the requested Apple event object. Instead, the relationship between a “container” and a specified object can be defined differently, depending on the key form. For example, the key form formRelativePosition indicates that the requested object is before or after its container.
Object specifier records that specify the key form formTest or formRange require key data that consists of several nested descriptor records, including additional object specifier records that identify either a group of elements to be tested or the boundary elements that demarcate a range. These object specifier records use two special descriptor types to specify containers: typeObjectBeingExamined (see page 6-19), which specifies a container that changes as a group of elements are tested one at a time, and typeCurrentContainer (see page 6-20), which specifies the container for a boundary element in a range. Both of these descriptor types require a data handle whose value is NIL, since they act much like variables whose value is supplied by the Apple Event Manager according to other information provided in the container hierarchy.
Key Form
The key form indicates how the key data should be interpreted. It can be specified by one of eight constants:
Keyword Descriptor type Data
keyAEKeyForm typeEnumerated formPropertyID
formName
formUniqueID
formAbsolutePosition
formRelativePosition
formTest
formWhose
formRange
The next section describes the key data that corresponds to each key form.
Key Data
The nature of the information provided by the key data depends both on the specified key form and on the descriptor type of the descriptor record for the key data. Table 6-1 summarizes these relationships for the standard key forms.
Table 6-1 Standard descriptor types used with keyAEKeyData(continued)
Key form Descriptor type Data
formPropertyID typeType Property ID for an element’s property
formName typeChar or other text type Element’s name
formUniqueID Any appropriate type A value that uniquely identifies an object within its container or across an application
formAbsolutePosition typeLongInteger Offset from beginning (positive) or end (negative) of container
typeAbsoluteOrdinal kAEFirst
kAEMiddle
kAELast
kAEAny
kAEAll
formRelativePosition typeEnumerated kAENext
kAEPrevious
formTest typeCompDescriptor (see Table 6-2 on page 6-16)
typeLogicalDescriptor (see Table 6-3 on page 6-17)
formRange typeRangeDescriptor (see Table 6-4 on page 6-20)
formWhose typeWhoseDescriptor (see Table 6-5 on page 6-42)
Most applications that resolve object specifier records need to support only the key forms formPropertyID, formName, formUniqueID, formAbsolutePosition, formRelativePosition, and formRange explicitly. You do not need to support these key forms for all object classes; for example, words usually do not have names, so most applications should return errAEEventNotHandled if they receive a request for a word by name.
If your application provides an object-counting function and an object-comparison function in addition to the appropriate object accessor functions, the Apple Event Manager can handle formTest automatically.
The Apple Event Manager uses the key form formWhose internally to optimize resolution of object specifier records that specify formTest. Applications that translate tests into their own query languages need to support formWhose explicitly. “Handling Whose Tests,” which begins on page 6-41, describes formWhose in detail.
You can define custom key forms and the format for corresponding data for use by your own application if necessary. If you think you need to do this, check with the Apple Event Registrar first to find out whether existing key forms or others still under development can be adapted to the needs of your application.
One simple kind of key form involves identifying an object on the basis of a specified property. For example, the corresponding data for key form formUniqueID (defined in the Apple Event Registry: Standard Suites) always consists of a unique ID for the requested object. This ID is stored as a property identified by the constant pID. The four-character code that corresponds to both formUniqueID and pID is 'ID '.
If you discover that you do need to define a custom key form based on a property, use the same four-character code for both the key form and the associated property.
The rest of this section describes how the key data for the other key forms shown in Table 6-1 identifies Apple event objects.
Key Data for a Property ID
The key data for formPropertyID is specified by a descriptor record of descriptor type typeType. The Apple Event Registry: Standard Suites defines constants for the standard property IDs.
An object specifier record for a property specifies cProperty as the object class ID, an object specifier record for the object that contains the property as the container, formPropertyID as the key form, and a constant such as pFont as the key data. For example, if you were sending a Set Data event to change the font of a word to Palatino®, you could specify the data for the object specifier record in the direct parameter as follows:
Keyword Descriptor type Data
keyAEDesiredClass typeType cProperty
keyAEContainer typeObjectSpecifier Object specifier record for word to which property belongs
keyAEKeyForm typeEnumerated formPropertyID
keyAEKeyData typeType pFont
In this example, the Set Data Apple event parameter identified by the keyword keyAETheData would specify Palatino as the value to which to set the specified property. The reply Apple event for a subsequent Get Data event that included an object specifier record for the same property would return Palatino in the parameter identified by the keyword keyAEResult.
Key Data for an Object’s Name
The key data for formName is specified by a descriptor record whose data consists of text, with a descriptor type such as typeChar or typeIntlText.
Figure 6-2 on page 6-10 includes two object specifier records that specify formName.
Key Data for a Unique ID
The key data for formUniqueID consists of a value that identifies an object. This ID must be unique either within the container, at a minimum, or unique across the application. A unique ID can be specified by a descriptor record of any appropriate type; for example, type typeInteger.
Key Data for Absolute Position
The key data for formAbsolutePosition consists of an integer that specifies either an offset or an ordinal position. For descriptor type typeLongInteger, the data is either a positive integer, indicating the offset of the requested element from the beginning of the container, or a negative integer, indicating its offset from the end of the container. The first object specifier record shown in Figure 6-2 on page 6-10 specifies formAbsolutePosition with key data that consists of the positive integer 1.
For descriptor type typeAbsoluteOrdinal, the data consists of one of these constants:
Constant Meaning
kAEFirst The first element in the specified container
kAEMiddle The element in the middle of the specified container
kAELast The last element in the specified container
kAEAny A single element chosen at random from the specified container
kAEAll All the elements in the specified container
If an object specifier record specifies kAEMiddle and the number of elements in the container is even, the Apple Event Manager rounds down; for example, the second word would be the “middle” word in a range of four words.
Key Data for Relative Position
The key data for formRelativePosition is specified by a descriptor record of type typeEnumerated whose data consists of one of these constants:
Constant Meaning
kAENext The Apple event object after the specified container
kAEPrevious The Apple event object before the specified container
The “container” can be a single Apple event object or a group of Apple event objects; the requested elements are located immediately before or immediately after it, not inside it.
If your application can locate objects of the same class by absolute position, it can easily locate the same objects by relative position. For example, all applications that support formAbsolutePosition can easily locate the table immediately after a container specified as another table named “Summary of Sales.”
Some applications may also be able to locate an object of one class before or after an object of another class. For example, a word processor might be able to locate the paragraph immediately after a container specified as a table named “Summary of Sales.”
Key Data for a Test
The key data for formTest is specified by either a comparison descriptor record or a logical descriptor record. If your application provides an object-counting function and an object-comparison function in addition to the appropriate object accessor functions, the Apple Event Manager can handle formTest for you. Some applications may perform tests more efficiently by translating them into the application’s own query language. For information about handling tests yourself, see “Handling Whose Tests,” which begins on page 6-41.
The container for objects that pass a test can be one or more Apple event objects. The objects specified are those in the container that pass the test specified by the key data. For example, an object specifier record can describe “the first row in which the First Name column equals ‘John’ and the Last Name column equals ‘Chapman’ in the table ‘MyAddresses’ of the database ‘SurfDB.’” To resolve such an object specifier record, the Apple Event Manager must evaluate a logical expression that applies the logical operator AND to two separate comparisons for each row: a comparison of the First Name column to the word “John” and a comparison of the Last Name column to the word “Chapman.”
The Apple Event Manager evaluates comparisons and logical expressions on the basis of the information in comparison descriptor records and logical descriptor records. A comparison descriptor record is a coerced AE record of type typeCompDescriptor that specifies an Apple event object and either another Apple event object or data for the Apple Event Manager to compare to the first object. The Apple Event Manager can also use the information in a comparison descriptor record to compare elements in a container, one at a time, either to an Apple event object or to data. The data for a comparison descriptor record consists of three keyword-specified descriptor records with the descriptor types and data shown in Table 6-2.
Table 6-2 Keyword-specified descriptor records for typeCompDescriptor
Keyword Descriptor type Data
keyAECompOperator typeType kAEGreaterThan
kAEGreaterThanEquals
kAEEquals
kAELessThan
kAELessThanEquals
kAEBeginsWith
kAEEndsWith
kAEContains
keyAEObject1 typeObjectSpecifier Object specifier data
typeObjectBeingExamined Value of data handle is NIL
keyAEObject2 typeObjectSpecifier Object specifier data for object to be compared
typeObjectBeingExamined Value of data handle is NIL
any other type (AEDesc) Data to be compared
The keyword keyAEObject1 identifies a descriptor record for the element that is currently being compared to the object or data specified by the descriptor record for the keyword keyAEObject2. Either object can be described by a descriptor record of type typeObjectSpecifier or typeObjectBeingExamined. A descriptor record of typeObjectBeingExamined acts as a placeholder for each of the successive elements in a container when the Apple Event Manager tests those elements one at a time. The keyword keyAEObject2 can also be used with a descriptor record of any other descriptor type whose data is to be compared to each element in a container.
You don’t have to support all the available comparison operators for all Apple event objects; for example, the “begins with” operator probably doesn’t make sense for objects of type cRectangle. It is up to you to decide which comparison operators are appropriate for your application to support, and how to interpret them.
If necessary, you can define your own custom comparison operators. If you think you need to do this, check with the Apple Event Registrar first to find out whether existing definitions of comparison operators or definitions still under development can be adapted to the needs of your application.
A logical descriptor record is a coerced AE record of type typeLogicalDescriptor that specifies a logical expression—that is, an expression that the Apple Event Manager evaluates to either TRUE or FALSE. The logical expression is constructed from a logical operator (one of the Boolean operators AND, OR, or NOT) and a list of logical terms to which the operator is applied. Each logical term in the list can be either another logical descriptor record or a comparison descriptor record. The Apple Event Manager short-circuits its evaluation of a logical expression as soon as one part of the expression fails a test. For example, if while testing a logical expression such as A AND B AND C the Apple Event Manager discovers that A AND B is not true, it will evaluate the expression to FALSE without testing C.
The data for a logical descriptor record consists of two keyword-specified descriptor records with the descriptor types and data shown in Table 6-3.
Table 6-3 Keyword-specified descriptor records for typeLogicalDescriptor
Keyword Descriptor type Data
keyAELogicalOperator typeEnumerated kAEAND
kAEOR
kAENOT
keyAELogicalTerms typeAEList One or more comparison or logical descriptor records
If the logical operator is AND or OR, the list can contain any number of logical terms, and the logical operator is applied to all the terms in the list. For example, the logical descriptor data shown in Figure 6-4 on page 6-19 consists of the logical operator AND and a list of logical terms that contains two comparison descriptor records. The entire logical descriptor record corresponds to the logical expression “the First Name column equals ‘John’ AND the Last Name column equals ‘Chapman.’” If the logical operator is NOT, the list must contain a single term.
Figure 6-3 shows four object specifier records that specify the container hierarchy for the first row in the table “MyAddresses” of the database “SurfDB” that meets a test. The object specifier record at the top of Figure 6-3 specifies the first row contained in the set of rows that form its container. The container for the first row is specified by an object specifier record for a set of rows that meet a test. The two object specifier records at the bottom of Figure 6-3 specify the table named “MyAddresses,” which contains the rows to be tested, in the database named “SurfDB.”
Figure 6-3 The container hierarchy for the first row in a table that meets a test
The object specifier record in Figure 6-3 for a set of rows that meet a test specifies formTest. The corresponding key data consists of the logical descriptor record shown in Figure 6-4, which applies the logical operator AND to two logical terms: a comparison descriptor record that specifies all the rows in the container (the table “MyAddresses”) in which the column named “First Name” equals “John,” and another comparison descriptor record that specifies all the rows in which the column named “Last Name” equals “Chapman.” A row in the table “MyAddresses” passes the test only if both comparison descriptor records evaluate as TRUE.
Figure 6-4 A logical descriptor record that specifies a test
The keyword-specified descriptor records with the keyword keyAEObject1 in
Figure 6-4 each consist of an object specifier record that identifies a column by name. The row for each column is specified by a descriptor record of typeObjectBeingExamined, which acts as a placeholder for each row as the Apple Event Manager tests successive rows in the table. The Apple event object specified by each of these object specifier records consists of a column in the row. The Apple Event Manager (with the help of an object-comparison function) compares the contents of the column in successive rows to the string identified by the keyword keyAEObject2 using the comparison operator identified by the keyword keyAECompOperator.
Key Data for a Range
The key data for formRange is specified by a range descriptor record, which is a coerced AE record of type typeRangeDescriptor that identifies two Apple event objects marking the beginning and end of a range of elements. The data for a range descriptor record consists of two keyword-specified descriptor records with the descriptor types and data shown in Table 6-4.
Table 6-4 Keyword-specified descriptor records in a descriptor record of type typeRangeDescriptor
Keyword Descriptor type Data
keyAERangeStart typeObjectSpecifier An object specifier record for the first Apple event object in the desired range
keyAERangeStop typeObjectSpecifier An object specifier record for the last Apple event object in the desired range
The elements that identify the beginning and end of the range, which are known as boundary objects, do not have to belong to the same object class as the elements in the range itself. If the boundary objects belong to the same object class as the elements in the range, the boundary objects are included in the range. For example, the range of tables specified by boundary elements that are also tables would include the two boundary tables.
The container for boundary objects is usually the same as the container for the entire range, in which case the container for a boundary object can be specified by a placeholder—that is, a descriptor record of type typeCurrentContainer whose data handle has the value NIL.
When AEResolve calls an object accessor function to locate a range of objects, the Apple Event Manager replaces the descriptor record of type typeCurrentContainer with a token for the container of each boundary object. When using AEResolve to resolve the object specifier record, your application doesn’t need to examine the contents of this token, because the Apple Event Manager keeps track of it. If your application attempts to resolve some or all of the object specifier record without calling AEResolve, the application may need to examine the token before it can locate the boundary objects. The token provided by the Apple Event Manager for a boundary object’s container is a descriptor record of type typeToken whose data handle refers to a structure of type ccntTokenRecord.
TYPE ccntTokenRecord =
RECORD
tokenClass: DescType; {class ID of container }
{ represented by token}
token: AEDesc; {token for current container}
END;
This data type is of interest only if you attempt to resolve an object specifier record for a range without calling AEResolve. Otherwise, the Apple Event Manager keeps track of the container.
Installing Entries in the Object Accessor Dispatch Tables
If the direct parameter for an Apple event consists of an object specifier record, your handler for the event should call the AEResolve function to resolve the object specifier record: that is, to find the Apple event objects or properties it describes. The AEResolve function resolves the object specifier record with the help of object accessor functions provided by your application. Your application installs entries for its object accessor functions in an object accessor dispatch table, which is used by the Apple Event Manager to map requests for Apple event objects or their properties to the appropriate object accessor functions.
After being called by AEResolve, an object accessor function should return a token that identifies (in whatever manner is appropriate for your application) the specified Apple event object or property. An object accessor function also returns a result code that indicates whether it found the Apple event object or property. The token, which is a descriptor record of data type AEDesc, can be of any descriptor type, including descriptor types you define yourself. For an overview of the way AEResolve works with your application’s object accessor functions to locate Apple event objects, see “Resolving Object Specifier Records,” which begins on page 6-4.
Each object accessor function provided by your application should either find elements of a specified object class contained in an Apple event object identified by a token of a specified descriptor type, or find properties of an Apple event object identified by a token of a specified descriptor type. To determine which object accessor function to dispatch, the Apple Event Manager uses the object class ID specified in an object specifier record and the descriptor type of the token that identifies the requested object’s container. For object accessor functions that find properties, you should specify the object class ID as the constant cProperty.
To install entries in your application’s object accessor dispatch table, use the AEInstallObjectAccessor function. For each object class and property your application supports, you should install entries that specify
n the object class of the requested Apple event object or property
n the descriptor type of the token used to identify the container for the requested Apple event object or property
n the address of the object accessor function that finds objects or properties of the specified object class in containers described by tokens of the specified descriptor type
n a reference constant
You provide this information in the first four parameters to the AEInstallObjectAccessor function. The fifth parameter allows you to indicate whether the entry should be added to your application’s object accessor dispatch table or the system object accessor dispatch table.
The system object accessor dispatch table is a table in the system heap that contains object accessor functions available to all processes running on the same computer. The object accessor functions in your application’s object accessor dispatch table are available only to your application. If AEResolve cannot find an object accessor function for the Apple event object class in your application’s object accessor dispatch table, it looks in the system object accessor dispatch table. If it doesn’t find an object accessor function there either, it returns the result code errAEAccessorNotFound.
If AEResolve successfully calls the appropriate object accessor function in either the application object accessor dispatch table or the system object accessor dispatch table, the object accessor function returns a token and result code. The AEResolve function uses the token and result code to continue resolving the object specifier record. If, however, the token identifies the final Apple event object or property in the container hierarchy, AEResolve returns the token for the final resolution in the theToken parameter.
If the AEResolve function calls an object accessor function in the system object accessor dispatch table, your Apple event handler may not recognize the descriptor type of the token returned by the function. If this happens, your handler should attempt to coerce the token to an appropriate descriptor type. If coercion fails, return the result code errAEUnknownObjectType. When your handler returns this result code, the Apple Event Manager attempts to locate a system Apple event handler that can recognize the token.
It is up to you to decide how many object accessor functions you need to write and install for your application. You can install one object accessor function that locates Apple event objects of several different object classes, or you can write separate object accessor functions for certain object classes. Similarly, you may want to use only one descriptor type for all the tokens returned by your object accessor functions, or you may want to use several descriptor types. The sections that follow provide examples of alternative approaches.
For more information about object accessor functions, see “Writing Object Accessor Functions,” which begins on page 6-28.
Installing Object Accessor Functions That Find Apple Event Objects
Listing 6-1 demonstrates how to add entries to your application’s object accessor dispatch table for the object class cText and three of its element classes: the object classes cWord, cItem, and cChar. In this example, the container for each of these object classes is identified by a token that consists of a descriptor record of descriptor type typeMyText.
Listing 6-1 Installing object accessor functions that find elements of different classes for container tokens of the same type
The first call to AEInstallObjectAccessor in Listing 6-1 adds an entry to the application’s object accessor dispatch table. This entry indicates that the AEResolve function should call the MyFindTextObjectAccessor function when resolving any Apple event object with the cText object class and a container identified by a token of descriptor type typeMyText. The other calls to AEInstallObjectAccessor in Listing 6-1 add entries for Apple event objects of object classes cWord, cItem, and cChar in a container identified by a token of descriptor type typeMyText. For example, because all the entries created by the code in Listing 6-1 specify the descriptor type typeMyText for the token that identifies the container, the AEResolve function calls the MyFindWordObjectAccessor function to locate a requested word regardless of whether the container for the word is a run of text, another word, a paragraph, or an item.
The fourth parameter for the AEInstallObjectAccessor function specifies a reference constant passed to your handler by the Apple Event Manager each time AEResolve calls your object accessor function. Your application can use this reference constant for any purpose. If your application doesn’t use the reference constant, you can use 0 as the value, as shown in Listing 6-1.
The last parameter for the AEInstallObjectAccessor function is a Boolean value that determines whether the entry is added to the system object accessor dispatch table (TRUE) or to your application’s object accessor dispatch table (FALSE).
If you add an object accessor function to the system object accessor dispatch table, the function that you specify must reside in the system heap. If there was already an entry in the system object accessor dispatch table for the same object class and container descriptor type, that entry is replaced unless you chain it to your system handler. You can do this the same way you chain a previously installed system Apple event handler to your own system handler. See the description of AEInstallEventHandler on page 4-62 for details.
sWARNING
Before an application calls a system object accessor function, system software has set up the A5 register for the calling application. For this reason, if you provide a system object accessor function, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system object accessor function may crash.s
The code shown in Listing 6-1 installs a separate object accessor function for each object class, even though the code specifies the same descriptor type for tokens that identify the containers for Apple event objects of each class. Most word-processing applications can specify the same object accessor function as well as the same token descriptor type for Apple event objects of these four classes, in which case the code shown in Listing 6-1 can be altered as shown in Listing 6-2.
Listing 6-2 Installing one object accessor function that finds elements of different classes for container tokens of one type
In some situations you may want to write different object accessor functions to locate Apple event objects of the same object class in containers identified by tokens of different descriptor types. For example, the code in Listing 6-3 installs two different object accessor functions: one that finds a word in a container identified by a token of type typeMyTextToken, and one that finds a word in a container identified by a token of typeMyGraphicTextToken.
Listing 6-3 Installing object accessor functions that find elements of the same class for container tokens of different types
Every application must provide one or more object accessor functions that can find Apple event objects in the default container, which is always identified by a token of descriptor type typeNull. Listing 6-4 demonstrates how to add entries to your application’s object accessor dispatch table for the object classes cWindow and cDocument. The container for each of these classes is identified by a token of descriptor type typeNull, which specifies an application’s default container.
Listing 6-4 Installing object accessor functions that locate elements of different classes in the default container
For any entry in your object accessor dispatch table, you can specify a wildcard value for the object class, for the descriptor type of the token used to identify the container, or for both. You specify a wildcard by supplying the typeWildCard constant when installing an entry into the object accessor dispatch table. A wildcard value matches all possible values.
If an object accessor dispatch table contains one entry for a specific object class and a specific token descriptor type, and another entry that is identical except that it specifies a wildcard value for either the object class or the token descriptor type, the Apple Event Manager dispatches the more specific entry. For example, if an object accessor dispatch table includes one entry that specifies the object class as cWord and the token descriptor type as typeMyTextToken, and another entry that specifies the object class as cWord and the token descriptor type as typeWildCard, the Apple Event Manager dispatches the object accessor function associated with the entry that specifies typeMyTextToken.
If you specify typeWildCard as the first parameter and typeMyToken as the second parameter for the AEInstallObjectAccessor function and no other entry in the dispatch table matches more exactly, the Apple Event Manager calls the object accessor function that you specify in the third parameter when resolving Apple event objects of any object class in containers identified by tokens of the typeMyToken descriptor type.
If you specify cText as the first parameter and typeWildCard as the second parameter for the AEInstallObjectAccessor function and no other entry in the dispatch table matches more exactly, the Apple Event Manager calls the object accessor function that you specify in the third parameter when resolving Apple event objects of the object class cText in containers identified by tokens of any descriptor type.
If you specify typeWildCard for both the first and second parameters of the AEInstallObjectAccessor function and no other entry in the dispatch table matches more exactly, the Apple Event Manager calls the object accessor function that you specify in the third parameter when resolving Apple event objects of any object class in containers identified by tokens of any descriptor type.
Once the Apple Event Manager finds a matching entry, whether exact or involving type typeWildCard, that is the only object accessor function it calls for that object class and token descriptor type. If that function fails, the Apple Event Manager won’t look for another matching entry in the same table.
Installing Object Accessor Functions That Find Properties
The Apple event object to which a property belongs is that property’s container. You should add entries to your application’s object accessor dispatch table that specify object accessor functions for finding properties in containers identified by tokens of various descriptor types. Object specifier records do not specify a property’s specific object class; instead, they specify the constant cProperty as the class ID for any property. Similarly, you should specify the constant cProperty as the object class for an object accessor function that can find any property of a container identified by a token of a given descriptor type. If you need to install different object accessor routines for finding properties of Apple event objects that belong to different object classes, you must use different descriptor types for the tokens that represent those Apple event objects.
For example, to specify an object accessor function that locates properties of Apple event objects identified by tokens of descriptor type typeMyToken, you can add a single entry to the object accessor dispatch table:
The code in this example adds an object accessor function to the application’s object accessor dispatch table that can find any property of any container identified by a token of descriptor type typeMyToken. If the second parameter were specified as typeWildCard, the MyFindPropertyObjectAccessor function would have to be capable of finding any property of any Apple event object in your application except for those found by handlers with more specific entries in the object accessor dispatch table.
Writing Object Accessor Functions
If the direct parameter for an Apple event consists of an object specifier record, your handler for the event should call the AEResolve function to resolve the object specifier record: that is, to find the Apple event objects or properties it describe. The AEResolve function resolves object specifier records with the help of object accessor functions provided by your application. For an overview of the way AEResolve works with your application’s object accessor functions to locate Apple event objects, see “Resolving Object Specifier Records,” which begins on page 6-4.
This section describes how to write object accessor functions. You need to read this section if your application supports the Core suite or any of the functional-area suites in the Apple Event Registry: Standard Suites.
Your application should provide object accessor functions that can find Apple event objects and their properties for all object classes supported by your application, including their corresponding properties and element classes. Because the Apple Event Manager dispatches object accessor functions according to the class ID of the requested Apple event object and the descriptor type of the token that identifies its container, you have a great deal of flexibility in deciding what object accessor functions you need to write for your application. The installation and dispatching of object accessor functions are described in “Installing Entries in the Object Accessor Dispatch Tables,” which begins on page 6-21.
For example, if your application is a word processor, one object accessor function will probably work equally well for Apple event objects of object classes cParagraph, cItem, and cWord located in containers identified by tokens of descriptor type myTextToken. If you use a single descriptor type for tokens that identify any containers in which objects of these three object classes can be found, you can dispatch requests for all such elements to the same object accessor function. However, the same word processor might use one descriptor type for tokens identifying containers of class cCell and another descriptor type for tokens identifying containers of class cColumn—in which case it would need an object accessor function for each descriptor type.
For each object class that your application supports, your application should also provide one object accessor function that can find all the properties of that object class, or one object accessor function that can find all the properties of several object classes.
Here’s the declaration for a sample object accessor function:
FUNCTION MyObjectAccessor (desiredClass: DescType;
containerToken: AEDesc;
containerClass: DescType;
keyForm: DescType; keyData: AEDesc;
VAR theToken: AEDesc;
theRefCon: LongInt): OSErr;
The AEResolve function passes the following information to your object accessor function: the object class ID of the requested Apple event objects, the object class of their container, a token that identifies the specific container in which to look for them, the key form and key data that specify how to locate them, and the reference constant associated with the object accessor function. Your object accessor function uses this information to locate the requested objects.
Most applications that resolve object specifier records need to support only the key forms formPropertyID, formName, formUniqueID, formAbsolutePosition, formRelativePosition, and formRange explicitly. You do not need to support these key forms for all object classes; for example, words usually do not have names, so most applications should return errAEEventNotHandled if they receive a request for a word by name.
If your application provides an object-counting function and an object-comparison function in addition to the appropriate object accessor functions, the Apple Event Manager can handle formTest automatically.
The Apple Event Manager uses the key form formWhose internally to optimize resolution of object specifier records that specify formTest. Only applications that translate tests into their own query languages need to support formWhose explicitly. “Handling Whose Tests,” which begins on page 6-41, describes formWhose in detail.
If your object accessor function successfully locates the requested Apple event objects, your application should return the noErr result code and a token that identifies them. The token can be of any descriptor type, as long as it is a descriptor record. For example, to identify a file, your application might use a descriptor record of descriptor type typeAlias or typeFSS. To identify an open document, your application might define its own descriptor type, such as typeMyDocToken, for a descriptor record whose data handle refers to a pointer to a document record. For more information about tokens, see “Defining Tokens” on page 6-39.
IMPORTANT
Object accessor functions must not have side effects that change the number or order of elements in a container while an object specifier record is being resolved. If the number of elements in a container is changed during the resolution of an object specifier record, the Apple Event Manager may not be able to locate all the elements.s
Writing Object Accessor Functions That Find Apple Event Objects
The first three listings in this section demonstrate how to write three object accessor functions that might be called in the following situation: An application receives a Get Data event with a direct parameter that consists of an object specifier record for the first word in the third paragraph of a document. The application’s handler for the Get Data event calls the AEResolve function to resolve the object specifier record. The AEResolve function first calls the application’s object accessor function for objects of class cDocument in containers identified by a token of descriptor type typeNull.
The AEResolve function passes these values to the MyFindDocumentObjectAccessor function shown in Listing 6-5: in the desiredClass parameter, the constant cDocument; in the containerToken parameter, a descriptor record of descriptor type typeNull with a data handle whose value is NIL; in the containerClass parameter, the constant typeNull; in the keyForm parameter, the constant formName; in the keyData parameter, a descriptor record of descriptor type typeText whose data consists of the string "MyDoc"; and the reference constant specified in the application’s object accessor dispatch table.
Listing 6-5 An object accessor function that locates Apple event objects of object class cDocument
The MyFindDocumentObjectAccessor function uses the information in the keyForm and keyData parameters to find the specified document. If it finds the Apple event object, MyFindDocumentObjectAccessor returns a token of descriptor type typeMyDocToken to AEResolve. The data handle for this token refers to a pointer to a document record (see Figure 6-5 on page 6-39). The MyFindDocumentObjectAccessor function returns this token and the noErr result code to the AEResolve function.
In the Get Data example, the token returned to AEResolve by the MyFindDocumentObjectAccessor function identifies the document “MyDoc.” The AEResolve function then calls the application’s object accessor function for objects of class cParagraph in containers identified by a token of descriptor type typeMyDocToken.
In this case, AEResolve passes these values to the MyFindParaObjectAccessor function shown in Listing 6-6: in the desiredClass parameter, the constant cParagraph; in the containerToken parameter, the token returned by the MyFindDocumentObjectAccessor function; in the containerClass parameter, the constant cDocument; in the keyForm parameter, the constant formAbsolutePosition; in the keyData parameter, a descriptor record with the typeLongInteger descriptor type and data that consists of the value 3 (indicating the third paragraph); and the reference constant specified in the application’s object accessor dispatch table.
Listing 6-6 An object accessor function that locates Apple event objects of object class cParagraph
FUNCTION MyFindParaObjectAccessor (desiredClass: DescType;
containerToken: AEDesc;
containerClass: DescType;
keyForm: DescType;
keyData: AEDesc;
VAR token: AEDesc;
theRefCon: LongInt): OSErr;
VAR
index: LongInt;
{MyFoundTextRecord is an application-defined data type }
{ consisting of three fields: start, ending, and docPtr}
foundParaRec: MyFoundTextRecord;
foundParaStart: LongInt;
foundParaEnd: LongInt;
foundDocRecPtr: MyDocumentRecordPtr;
success: Boolean;
BEGIN
IF keyForm = formAbsolutePosition THEN
BEGIN
{get the index of the paragraph from the key data}
The MyFindParaObjectAccessor function uses another application-defined function, MyGetPara, to search the data structures associated with the document and find the desired paragraph. If it finds the paragraph, MyGetPara returns a value that identifies the beginning of the paragraph, a value that identifies the end of the paragraph, and a pointer to the document (which MyGetPara gets from the containerToken parameter). The MyFindParaObjectAccessor function returns an application-defined token that contains this information. This token is of descriptor type typeMyTextToken; it describes a range of characters that can be used to identify any range of text, including a paragraph or a word. The MyFindParaObjectAccessor function returns this token and the noErr result code to the AEResolve function.
In the Get Data example, the token returned to AEResolve by the MyFindParaObjectAccessor function identifies the third paragraph in the document “MyDoc.” The AEResolve function then calls the application’s object accessor function for objects of class cWord in containers identified by a token of descriptor type typeMyTextToken.
In this case, the AEResolve function passes these values to the MyFindWordObjectAccessor function shown in Listing 6-7: in the desiredClass parameter, the constant cWord; in the containerToken parameter, the token returned by the MyFindParaObjectAccessor function (a token of descriptor type typeMyTextToken that identifies a paragraph); in the containerClass parameter, the constant cParagraph; in the keyForm parameter, the constant formAbsolutePosition; in the keyData parameter, a descriptor record with the typeLongInteger descriptor type and data that consists of the value 1 (indicating the first word); and the reference constant specified in the application’s object accessor dispatch table.
The MyFindWordObjectAccessor function uses another application-defined function, MyGetWord, to search the paragraph to find the desired word. If it finds the word, MyGetWord returns a value that identifies the beginning of the word, a value that identifies the end of the word, and a pointer to the document (which MyGetWord gets from the containerToken parameter). The MyFindWordObjectAccessor function returns a token that contains this information. This token is also of descriptor type typeMyTextToken; in this case, the token identifies a specific word. The MyFindWordObjectAccessor function returns this token and the noErr result code to the AEResolve function, which in turn returns the token to the Get Data event handler that originally called AEResolve.
Listing 6-7 An object accessor function that locates Apple event objects of object class cWord
Listing 6-5 on page 6-30 shows an object accessor function that locates a document in the default container. Every application must provide one or more object accessor functions that can find Apple event objects in the default container, which is always identified by a descriptor record of descriptor type typeNull. Listing 6-8 provides another example of an object accessor function that locates an Apple event object in the default container. If the MyFindWindowObjectAccessor function shown in Listing 6-8 were installed in an application’s object accessor dispatch table, the AEResolve function would call it as necessary to locate an object of class cWindow in a container identified by a token of descriptor type typeNull.
Listing 6-8 An object accessor function that locates Apple event objects of object class cWindow
FUNCTION MyFindWindowObjectAccessor (desiredClass: DescType;
containerToken: AEDesc;
containerClass: DescType;
keyForm: DescType;
keyData: AEDesc;
VAR token: AEDesc;
theRefCon: LongInt): OSErr;
VAR
windowName: Str255;
actSize: Size;
windTitle: Str255;
window: WindowPtr;
index, iLoop: Integer;
found: Boolean;
BEGIN
IF keyForm = formName THEN
BEGIN
{get the name of the window to find from the keyData }
{ parameter. MyGetStringFromDesc gets data out of an }
{ AEDesc and returns a string and the string's size}
The keyForm parameter of the MyFindWindowObjectAccessor function describes how the function should interpret the keyData parameter. If the key form is formName, then the key data contains the name of the window to locate. If the key form is formAbsolutePosition, the key data contains the position of the window to locate in the window list; for example, a value of 1 identifies the frontmost window.
The MyFindWindowObjectAccessor function supports only the formName and formAbsolutePosition key forms. Your object accessor functions should support all key forms that make sense for the kinds of objects the functions can locate.
For the formName keyword, the MyFindWindowObjectAccessor function starts with the frontmost window and compares the window’s title to the name specified by the keyData parameter. It continues this search until it reaches either the end of the window list or finds a match. If the MyFindWindowObjectAccessor function finds a match, it uses the AECreateDesc function to create a descriptor record for the token, specifying the application-defined typeMyWindow descriptor type and the data for this descriptor type as a window pointer.
The MyFindWindowObjectAccessor function then sets its function result appropriately, and the AEResolve function either returns this function result and token, or uses the returned token to request the next Apple event object in the container hierarchy, such as a document in the window.
Writing Object Accessor Functions That Find Properties
The Apple event object to which a property belongs is that property’s container. Your application should provide an object accessor function for finding properties in containers identified by tokens of various descriptor types. Your application does not need to be given a property’s specific object class in order to find that property; instead, you can specify the object class ID for any property with the constant cProperty. Thus, you can write a single object accessor function that can find any property of an object identified by a token of a given descriptor type.
To install such an object accessor function, you can add a single entry to the object accessor dispatch table that specifies the desired object class as cProperty for a given token descriptor type. For example, Listing 6-9 shows an object accessor function that identifies any property of a window.
Listing 6-9 An object accessor function that identifies any property of a window
FUNCTION MyFindPropertyOfWindowObjectAccessor
(desiredClass: DescType;
containerToken: AEDesc;
containerClass: DescType;
keyForm: DescType; keyData: AEDesc;
VAR token: AEDesc;
theRefCon: LongInt): OSErr;
VAR
theProperty: DescType;
BEGIN
MyFindPropertyOfWindowObjectAccessor := noErr;
MyGetPropFromKeyData(keyData, theProperty);
IF keyForm = formPropertyID THEN
BEGIN
IF theProperty = pName THEN
{create token that identifies name property of the }
{create tokens for other properties as appropriate}
ELSE
MyFindPropertyOfWindowObjectAccessor :=
kErrorPropNotFound;
END
ELSE
MyFindPropertyOfWindowObjectAccessor :=
kKeyFormNotSupported;
END;
The MyFindPropertyOfWindowObjectAccessor function takes a token that identifies a window and creates a token that identifies the requested property of that window. See Figure 6-6 on page 6-40 for an illustration of the logical organization of a token of descriptor type typeMyWindowProp.
This simplified example merely translates information about the requested property and the window to which it belongs into the form of a token of type typeMyWindowProp. This token can then be used by Apple event handlers to identify the corresponding window and its property, so that a handler can either retrieve the value of the property (for example, a Get Data handler) or change the value of the property (for example, a Set Data handler). Like other tokens, a token that identifies a property should always contain a reference to the corresponding property and the object to which it belongs—not a copy of the data for that object’s property.
Defining Tokens
It is up to you to decide how many token descriptor types you need to define for your application. In many cases you may be able to define one token that can identify Apple event objects of several different object classes, such as a token of type typeMyTextToken that identifies Apple event objects of object classes cText, cWord, cItem, and cChar. In other cases you may need to define specific token descriptor types for specific object classes.
For example, the MyFindDocumentObjectAccessor routine shown in Listing 6-5 on page 6-30 returns a token of descriptor type typeMyDocToken, which identifies a document record.
CONST {application-defined token}
typeMyDocToken = 'docr'; {identifies a document record}
Figure 6-5 shows the logical arrangement of a descriptor record of descriptor type typeMyDocToken whose data is specified by a pointer to a document record.
Figure 6-5 Descriptor record for an application-defined token that identifies a document
The MyFindPropertyOfWindowObjectAccessor routine shown in Listing 6-9 returns a token of descriptor type typeMyWindowProp for every property that it can locate.
CONST {application-defined token}
typeMyWindowProp = 'wprp'; {a window pointer and a }
{ property ID}
Figure 6-6 shows the logical arrangement of a descriptor record of descriptor type typeMyWindowProp that identifies the bounds property of a window. Its data consists of a window pointer and the constant pBounds. The application can use this token either to return or to change the window’s bounds setting, depending on the Apple event that specified the property. If the token specified pName instead, the application could use it either to return the window’s name as a string or to change the window’s name.
Figure 6-6 Descriptor record for an application-defined token that identifies the pbounds property of a window
A token’s data should always contain a reference to the corresponding Apple event objects—not a copy of the data for those objects. This allows the same token to be used for both reading and writing tokens.
It’s often possible to use the same token type for objects of several object classes, or for both an object of a given class and one of its properties. A token’s data is private to your application and can be organized in any way that is convenient.
When an object accessor function that supports key form formRange locates a range of Apple event objects, it should normally return a descriptor list (AEDescList) of tokens for the individual objects. A typical exception is an object accessor function that returns a range of objects of class cText, which should return a single token representing the entire range. For example, an object accessor function that finds “all the characters from char 1 to char 1024” should return a token that consists of a list of 1024 objects, each of class cChar, whereas an object specifier function that finds “all the text from char 1 to char 1024” should return a single token for a single item of class cText that is 1024 characters long.
A token is valid only until the Apple Event Manager has located the requested element in the container the token represents and returned another token for the element. The Apple Event Manager disposes of intermediate tokens after it finishes resolving an object specifier record, but one token is always left over—the token that identifies the specified Apple event object or objects. Your application should dispose of this final token by calling the AEDisposeToken function, which in turn calls your application’s token disposal function (if one exists), an optional object callback function that disposes of a token. See page 6-99 for the declaration of a token disposal function.
If your application does not provide a token disposal function, the Apple Event Manager uses the AEDisposeDesc function to dispose of tokens. This function does the job as long as disposing of tokens involves nothing more than simply disposing of a descriptor record. Otherwise, you need to provide a custom token disposal function. For example, suppose the data field of a token descriptor record contains a handle to a block that in turn contains references to memory for the Apple event object referred to by the token. In this case, the application should provide a token disposal function that performs the tasks required to dispose of the token and any associated structures.
Handling Whose Tests
If your application provides an object-counting function and an object-comparison function in addition to the appropriate object accessor functions, the Apple Event Manager can resolve object specifier records that specify formTest without any other assistance from your application. The Apple Event Manager translates object specifier records of key form formTest into object specifier records of key form formWhose. This involves collapsing the key form and key data from two object specifier records in a container hierarchy into one object specifier record with the key form formWhose.
Some applications may find it more efficient to translate whose tests into their own query languages rather than letting the Apple Event Manager handle the tests. This is useful only for applications that can make use of a test combined with either an absolute position or a range to locate objects. If you want the Apple Event Manager to let your application handle whose tests, set the kAEIDoWhose flag in the callbackFlags parameter of the AEResolve function. If for any reason one of your application’s object accessor functions chooses not to handle a particular whose descriptor record, it should return errAEEventNotHandled as the result code, and the Apple Event Manager will try again using the original object specifier records, just as if the kAEIDoWhose flag were not set.
The key data for formWhose is specified by a whose descriptor record, which is a coerced AE record of descriptor type typeWhoseDescriptor. The data for a whose descriptor record consists of the two keyword-specified descriptor records shown in Table 6-5.
Table 6-5 Keyword-specified descriptor records for typeWhoseDescriptor
Keyword Descriptor type Data
keyAEIndex typeLongInteger Offset of requested element in group of elements that pass a test
typeAbsoluteOrdinal kAEFirst
kAEMiddle
kAELast
kAEAny
kAEAll
typeWhoseRange Whose range descriptor record
keyAETest typeCompDescriptor Comparison descriptor record
typeLogicalDescriptor Logical descriptor record
A whose descriptor record is never created directly by an application. The Apple Event Manager creates a whose descriptor record whenever an object specifier record of key form formTest is used to describe the container for elements described by an object specifier record of key form formAbsolutePosition or formRange, with some exceptions as noted in this section.
For example, Figure 6-3 on page 6-18 shows four object specifier records that show the container hierarchy for the first row that meets a test in the table “MyAddresses” of the database “SurfDB.” The top two object specifier records in that figure use the key forms formAbsolutePosition and formTest to describe elements in a container. When it receives these two object specifier records, the Apple Event Manager collapses them into one, as shown in Figure 6-7. It then calls the application’s object-counting function to find out how many objects of class cRow the table contains and the object-comparison function to test the rows in the table until it finds the first row that passes the test.
Figure 6-7 A container hierarchy created by the Apple Event Manager using a whose descriptor record
If the elements to be tested are described by an object specifier record of key form formAbsolutePosition or formRange but are not of the same object class as their container, the Apple Event Manager cannot collapse the existing object specifier records into a whose descriptor record. Instead, the Apple Event Manager creates a whose descriptor record as if a third object specifier record of key form formAbsolutePosition and kAEAll were inserted between the object specifier record for the container and that for the tested elements. For example, the Apple Event Manager would interpret a request for “character 1 of word whose first letter = ‘a’” as “character 1 of every word whose first letter = ‘a’”.
When an object specifier record of key form formTest is used to describe the container for elements described by an object specifier record of key form formRange, the Apple Event Manager will, under certain conditions, coerce the corresponding range descriptor record to a whose range descriptor record, which is a coerced AE record of typeWhoseRange. The data for a whose range descriptor record consists of two keyword-specified descriptor records with the descriptor types and data shown in
Table 6-6.
Table 6-6 Keyword-specified descriptor records for typeWhoseRange
Keyword Descriptor type Data
keyAEWhoseRangeStart typeLongInteger Offset of beginning of range
typeAbsoluteOrdinal kAEFirst
kAEMiddle
kAELast
kAEAny
kAEAll
keyAEWhoseRangeStop typeLongInteger Offset of end of range
typeAbsoluteOrdinal kAEFirst
kAEMiddle
kAELast
kAEAny
kAEAll
A whose range descriptor record describes the absolute position of the boundary elements, within the set of all elements that pass a test, that identify the beginning and end of the desired range.
The Apple Event Manager coerces a range descriptor record to a whose range descriptor record if the specified container and its elements are of the same class, if the container for the specified range of elements is a group of Apple event objects that pass a test, and if the boundary objects in the original range descriptor record meet these conditions:
n Both boundary objects are of the same object class as the Apple event objects in the range they specify.
n The object specifier record for each boundary object specifies its container with a descriptor record of descriptor type typeCurrentContainer.
n The object specifier record for each boundary object specifies a key form of formAbsolutePosition.
If these conditions are not met, the Apple Event Manager doesn’t create a whose range descriptor record. Instead, as described earlier in this section, the Apple Event Manager creates a whose descriptor record as if the original request specified every element that passed the test.
If your application sets the kAEIDoWhose flag in the callbackFlags parameter of AEResolve, you should provide object accessor functions that can handle formWhose. These functions should coerce the whose descriptor record specified as key data for an object specifier record to an AE record and extract the data from the AE record by calling the AEGetKeyPtr and AEGetKeyDesc functions. If the keyword-specified descriptor record with the keyword keyAEIndex specifies descriptor type typeWhoseRange, your object accessor function must also coerce that descriptor record to an AE record and extract the data. Your object accessor function should then attempt to locate the requested objects and, if successful, return a token that identifies them.
If your application sets the kAEIDoWhose flag and attempts to resolve every whose descriptor record it receives, the Apple Event Manager does not attempt to resolve object specifier records of any key form. The object-counting and object-comparison functions are never called, and your application is solely responsible for determining the formats and types of all tokens.
Writing Object Callback Functions
If an Apple event parameter consists of an object specifier record, your handler for the Apple event typically calls AEResolve to begin the process of locating the requested Apple event object or objects. In turn, AEResolve calls object accessor functions and, if necessary, object callback functions provided by your application.
Every application that supports Apple event objects should provide object accessor functions that can locate Apple event objects belonging to any of the supported object classes. For an overview of the way AEResolve calls object accessor functions to locate Apple event objects described by object specifier records, see “Resolving Object Specifier Records,” which begins on page 6-4.
In addition to object accessor functions, your application can provide up to seven object callback functions:
n An object-counting function counts the number of elements of a specified class in a specified container, so that the Apple Event Manager can determine how many elements it must examine to find the element or elements that pass a test. Your application must provide one object-counting function to handle object specifier records that specify tests. (See “Writing an Object-Counting Function,” which begins on page 6-48.)
n An object-comparison function compares one element either to another element or to a descriptor record and returns either TRUE or FALSE. Your application must provide one object-comparison function to handle object specifier records that specify tests. (See “Writing an Object-Comparison Function” on page 6-50.)
n A token disposal function disposes of a token after your application calls the AEDisposeToken function. If your application doesn’t provide a token disposal function, the Apple Event Manager uses the AEDisposeDesc function instead. Your application must provide a token disposal function if it requires more than a call to AEDisposeDesc to dispose of one of its tokens. This is true, for example, if your application supports marking by modifying its own data structures. (See page 6-99 for the declaration of a token disposal function.)
n An error callback function gives the Apple Event Manager an address to which to write the descriptor record it is currently working with if an error occurs while AEResolve is attempting to resolve an object specifier record. Your application is not required to provide an error callback function. (See page 6-100 for the declaration of an error callback function.)
n Three marking callback functions are used by the Apple Event Manager to get a mark token from your application, to mark specific Apple event objects, and to pare down a group of marked Apple event objects. Your application must provide all three marking functions if it supports marking. (See “Writing Marking Callback Functions” on page 6-53.)
To make your object callback functions available to the Apple Event Manager, use the AESetObjectCallbacks function:
myErr := AESetObjectCallbacks (@MyCompareObjects,
@MyCountObjects, @MyDisposeToken,
@MyGetMarkToken, @MyMark,
@MyAdjustMarks, @MyGetErrDesc);
Each parameter to the AESetObjectCallbacks function consists of either a pointer to the corresponding application-defined function or NIL if no function is provided. The AESetObjectCallbacks function sets object callback functions that are available only to your application. To set system object callback functions, which are available to all applications and processes running on the same computer, use the AEInstallSpecialHandler function as described on page 4-100.
To handle object specifier records that specify tests, your application must provide an object-counting function and an object-comparison function. The Apple Event Manager calls your application’s object-counting function to determine the number of Apple event objects in a specified container that need to be tested. The Apple Event Manager calls your application’s object-comparison function when it needs to compare one Apple event object to either another Apple event object or to a value in a descriptor record.
If your application does not provide a token disposal function, the Apple Event Manager uses the AEDisposeDesc function to dispose of tokens. This function does the job as long as disposing of tokens involves nothing more than simply disposing of a descriptor record. Otherwise, you need to provide custom token disposal function. For example, suppose the data field of a token descriptor record contains a handle to a block that in turn contains references to storage for the Apple event object referred to by the token. In this case, the application can provide a token disposal function that performs the tasks required to dispose of the token and any associated structures.
Whenever more than one Apple event object passes a test, AEResolve can either return a list of tokens or make use of a target application’s ability to mark its own objects. Sometimes a list of tokens can become unmanageably large. For example, if a Get Data event asks for the names and addresses of all customers with a specified zip code who have purchased a specified product, the object accessor function that locates all the customers with the specified zip code might return a list of many thousands of tokens; the elements identified by those tokens would then have to be tested for the specified product. However, if your application uses some method of marking objects, you can choose simply to mark the requested objects rather than returning a list of tokens. “Writing Marking Callback Functions” on page 6-53 describes how to do this. If your application supports marking by modifying its own data structures, you must provide a token disposal function.
When one of your application’s Apple event handlers calls the AEResolve function, the handler should pass a value in the callbackFlags parameter that specifies whether your application supports whose descriptor records or provides marking callback functions. You can add the following constants, as appropriate, to provide a value for the callbackFlags parameter:
CONST kAEIDoMinimum = $0000; {does not handle whose tests or }
{ provide marking callbacks}
kAEIDoWhose = $0001; {supports key form formWhose}
For example, this code instructs the Apple Event Manager to call any marking functions previously set with the AESetObjectCallbacks function while resolving the object specifier record in the objectSpecifier parameter:
If any of the marking callback functions are not installed, AEResolve returns the error errAEHandlerNotFound.
IMPORTANT
If your application doesn’t specify kAEIDoWhose, the Apple Event Manager attempts to resolve all object specifier records of key form formTest. To do so, the Apple Event Manager uses your application’s object-counting and object-comparison functions, and returns a token of type typeAEList.
If your application does specify kAEIDoWhose, the Apple Event Manager does not attempt to resolve object specifier records of any key form. In this case, the object-counting and object-comparison functions are never called; your application determines the formats and types of all tokens; and your application must interpret whose descriptor records created by the Apple Event Manager during the resolution of object specifier records. For more information, see “Handling Whose Tests,” which begins on page 6-41.s
Writing an Object-Counting Function
To handle object specifier records that specify tests, your application should provide an object-counting function (unless it specifies kAEIDoWhose as just described). Your object-counting function should be able to count the number of elements of a given object class in a given container. For example, if your application supports Apple event objects that belong to the object class cText in the Text suite, your application should provide an object-counting function that can count Apple event objects of each element class listed in the definition of cText in the Apple Event Registry: Standard Suites. In this case, your application should provide an object-counting function that can count the number of words, items, or characters in a text object.
You specify your object-counting function with the AESetObjectCallbacks function. Whenever it is resolving an object specifier record and it requires a count of the number of elements in a given container, the Apple Event Manager calls your object-counting function.
Here’s the declaration for a sample object-counting function:
FUNCTION MyCountObjects (desiredClass: DescType;
containerClass: DescType;
containerToken: AEDesc;
VAR result: LongInt): OSErr;
The Apple Event Manager passes the following information to your object-counting function: the object class ID of the Apple event objects to count, the object class of their container, and a token identifying their container. (The container class can be useful if you want to use one token type for several object classes.) Your object-counting function uses this information to count the number of Apple event objects of the specified object class in the specified container. After counting the Apple event objects, your application should return the noErr result code and, in the result parameter, the number of Apple event objects counted.
Listing 6-10 shows an application-defined function, MyCountObjects, that counts the number of objects for any object class supported by the application.
Listing 6-10 An object-counting function
FUNCTION MyCountObjects (desiredClass: DescType; containerClass: DescType;
containerToken: AEDesc; VAR result: LongInt): OSErr;
{this app does not support any other object classes}
MyCountObjects := kObjectClassNotFound;
END;
Writing an Object-Comparison Function
To handle object specifier records that specify tests, your application should provide an object-comparison function (unless it specifies kAEIDoWhose as described on page 6-48). Your object-comparison function should be able to compare one Apple event object to another Apple event object or to another descriptor record.
You specify your object-comparison function with the AESetObjectCallbacks function. Whenever it is resolving object specifier records and needs to compare the value of an Apple event object with another object or with data, the Apple Event Manager calls your object-comparison function.
Here’s the declaration for a sample object-comparison function:
FUNCTION MyCompareObjects (comparisonOperator: DescType;
object: AEDesc;
objectOrDescToCompare: AEDesc;
VAR result: Boolean): OSErr;
The Apple Event Manager passes the following information to your object-comparison function: a comparison operator that specifies how the two objects should be compared, a token for the first Apple event object, and either a token that describes the Apple event object to compare or a descriptor record.
It is up to your application to interpret the comparison operators it receives. The meaning of comparison operators differs according to the Apple event objects being compared, and not all comparison operators apply to all object classes. After successfully comparing the Apple event objects, your object-comparison function should return the noErr result code and, in the result parameter, a Boolean value specifying TRUE if the result of the comparison is true and FALSE otherwise. If for any reason your comparison function is unable to compare the specified Apple event objects, it should return the result code errAEEventNotHandled; then the Apple Event Manager will try an alternative method of comparing the Apple event objects, such as calling the equivalent system object-comparison function, if one exists.
Your object-comparison function should be able to compare an Apple event object belonging to any object class with another Apple event object. Your function should also be able to compare two Apple event objects with different object classes, if appropriate. For example, an object-comparison function for a word-processing application might be asked to compare the First Name column of a specified row in a table with the first word on a specified page—that is, to compare an Apple event object of object class cColumn with an Apple event object of object class cWord. You must decide what kinds of comparisons make sense for your application.
The Apple Event Registry: Standard Suites defines standard comparison operators. Here is a list of the constants that correspond to these comparison operators:
CONST
kAEGreaterThan = '> ';
kAEGreaterThanEquals = '>= ';
kAEEquals = '= ';
kAELessThan = '< ';
kAELessThanEquals = '<= ';
kAEBeginsWith = 'bgwt';
kAEEndsWith = 'ends';
kAEContains = 'cont';
The comparison operators always relate the first operand to the second. For example, the constant kAEGreaterThan means that the object-comparison function should determine whether or not the value of the first operand is greater than the value of the second operand. For more information, see page 6-90.
Listing 6-11 shows an application-defined function, MyCompareObjects, that compares two Apple event objects of any object class supported by the application.
Listing 6-11 Object-comparison function that compares two Apple event objects
FUNCTION MyCompareObjects (comparisonOperator: DescType;
theObject: AEDesc;
objectOrDescToCompare: AEDesc;
VAR result: Boolean): OSErr;
BEGIN
result := FALSE;
{compare two objects for equivalence}
IF comparisonOperator = kAEEquals THEN
MyCompareObjects := MyCompEquals(theObject,
objectOrDescToCompare,
result)
ELSE
{compare two objects for greater than}
IF comparisonOperator = kAEGreaterThan THEN
MyCompareObjects := MyCompGreaterThan(theObject,
objectOrDescToCompare,
result)
ELSE
{compare two objects for less than}
IF comparisonOperator = kAELessThan THEN
MyCompareObjects := MyCompLessThan(theObject,
objectOrDescToCompare,
result)
ELSE
{this app does not support any other comparison operators}
MyCompareObjects := errAEEventNotHandled;
END;
The MyCompareObjects function calls a separate application-defined routine for each comparison operator. In each case, the application-defined routine that actually performs the comparison can compare an Apple event object with either another Apple event object or with a descriptor record’s data. If for any reason the comparison cannot be performed, the MyCompareObjects function returns the result code errAEEventNotHandled.
Writing Marking Callback Functions
Marking callback functions allow applications such as databases that can mark their own objects to take advantage of that capability when resolving object specifier records. Instead of returning a list of tokens for a group of Apple event objects that pass a test, your application can simply mark the Apple event objects and return a token that identifies how they have been marked. In this way, you can speed the resolution of complex object specifier records and reduce the amount of memory you need to allocate for tokens.
The use of marking callback functions is optional and usually makes sense if (a) you can reasonably expect that the tokens created in the process of resolving some object specifier records might not all fit in memory at once or (b) your application already uses a marking mechanism. If you want the Apple Event Manager to use marking callback functions provided by your application, you must add the kAEIDoMarking constant to the value of the callbackFlags parameter for the AEResolve function. If for any reason your application cannot mark a requested set of Apple event objects, it should return errAEEventNotHandled as the result code, and the Apple Event Manager will attempt to continue resolving the object specifier record by some other method, such as using a system marking function, if one exists.
If your application supports marking callback functions, it must provide three functions with declarations that match these examples:
FUNCTION MyGetMarkToken (containerToken: AEDesc;
containerClass: DescType;
VAR Result: AEDesc): OSErr;
FUNCTION MyMark (theToken: AEDesc; markToken: AEDesc;
markCount: LongInt): OSErr;
FUNCTION MyAdjustMarks (newStart, newStop: LongInt;
markToken: AEDesc): OSErr;
For more detailed information about these sample declarations, see “Object Callback Functions,” which begins on page 6-96.
To resolve a given object specifier record with the aid of the marking callback functions provided by your application, the Apple Event Manager first calls your application’s mark token function (MyGetMarkToken), passing a token that identifies the container of the elements to be marked in the containerToken parameter and the container’s object class in the containerClass parameter. The mark token function returns a mark token. A mark token, like other tokens, can be a descriptor record of any type; however, unlike other tokens, it identifies the way your application marks Apple event objects during the current session while resolving a single test. A mark token does not identify a specific Apple event object; rather, it allows your application to associate a group of objects with a marked set.
After it receives the mark token, the Apple Event Manager can call your application’s object-marking function (MyMark) repeatedly to mark specific Apple event objects. The Apple Event Manager passes the following information to your marking function: in the theToken parameter, a token for the object to be marked (obtained from the appropriate object accessor function); in the markToken parameter, the current mark token; and in the markCount parameter, the mark count. The mark count indicates the number of times the Apple Event Manager has called the marking function for the current mark token. Your application should associate the mark count with each Apple event object it marks.
When the Apple Event Manager needs to identify either a range of elements or the absolute position of an element in a group of Apple event objects that pass a test, it can use your application’s mark-adjusting function (MyAdjustMarks) to unmark objects that it has previously marked. For example, suppose an object specifier record specifies “any row in the table ‘MyCustomers’ for which the City column is ‘San Francisco.’” The Apple Event Manager first uses the appropriate object accessor routine to locate all the rows in the table for which the City column is “San Francisco” and calls the application’s marking function repeatedly to mark them. It then generates a random number between 1 and the number of rows it found that passed the test and calls the application’s mark-adjusting function to unmark all the rows whose mark count does not match the randomly generated number. If the randomly chosen row has a mark count value of 5, the Apple Event Manager passes the mark-adjusting function 5 in both the newStart parameter and the newStop parameter, and the current mark token in the markToken parameter. The newStart and newStop parameters identify the beginning and end of the new set of marked objects that the mark-adjusting function will create by unmarking those previously marked objects not included in the new set.
When the Apple Event Manager calls your mark-adjusting function, your application must dispose of any data structures that it may have created to mark the previously marked objects. The Apple Event Manager calls your mark-adjusting function only once for a given mark token.
A mark token is valid until the Apple Event Manager either disposes of it (by calling AEDisposeToken) or returns it as the result of the AEResolve function. If the final result of a call to the AEResolve function is a mark token, the Apple event objects currently marked for that mark token are those specified by the object specifier record passed to AEResolve, and your application can proceed to do whatever the Apple event has requested. Note that your application is responsible for disposing of a final mark token with a call to AEDisposeToken, just as for any other final token.
If your application supports marking, it should also provide a token disposal function. When the Apple Event Manager calls AEDisposeToken to dispose of a mark token that is not the final result of a call to AEResolve, the subsequent call to your token disposal function lets you know that you can unmark the Apple event objects marked with that mark token. A call to AEDisposeDesc to dispose of a mark token (which would occur if you did not provide a token disposal function) would leave the objects marked.
Creating Object Specifier Records
If your application creates and sends Apple events that require the target application to locate Apple event objects, your application must create object specifier records for those events. This section describes how to use the four keyword-specified descriptor records described in “Descriptor Records Used in Object Specifier Records,” which begins on page 6-8, to specify the object class ID, container, key form, and key data for an object specifier record.
Because the internal structure of an object specifier record is nearly identical to the internal structure of an AE record, it is possible to use AECreateList, AEPutPtr, and AEPutKeyDesc to add the four keyword-specified descriptor records to an AE record, then use AECoerceDesc to coerce the AE record to a descriptor record of type typeObjectSpecifier. However, it is usually preferable to use the CreateObjSpecifier function to accomplish the same goal. The CreateObjSpecifier function adds the keyword-specified descriptor records directly to an object specifier record, thus eliminating several steps that are required if you create an AE record first. The instructions that follow make use of CreateObjSpecifier.
To specify the class ID for an object specifier record, your application can specify the appropriate class ID value as the desiredClass parameter for the CreateObjSpecifier function, which uses it to create a keyword-specified descriptor record with the keyword keyAEDesiredClass as part of an object specifier record.
To specify the container for an object specifier record, your application must create a keyword-specified descriptor record with the keyword keyAEContainer that fully describes the container of the Apple event object. Because this container is usually another Apple event object, the container is usually specified by another object specifier record.
To specify the complete container hierarchy of an Apple event object, your application must create a series of nested object specifier records, starting with the object specifier record for the Apple event object whose container is outermost. With the exception of this first object specifier record, each object specifier record specifies another object specifier record in the chain as a container.
For example, Figure 6-2 on page 6-10 shows a series of nested object specifier records that specify the first row of a table named “Summary of Sales” in a document named “Sales Report.” The logical organization of the same object specifier records is summarized in Table 6-7.
Table 6-7 Nested object specifier records that describe a container hierarchy
Keyword Descriptor type Data
keyAEDesiredClass typeType cRow
keyAEContainer typeObjectSpecifier (see indented record)
keyAEDesiredClass typeType cTable
keyAEContainer typeObjectSpecifier (see indented record)
keyAEDesiredClass typeType cDocument
keyAEContainer typeNull Data handle is NIL
keyAEKeyForm typeEnumerated formName
keyAEKeyData typeChar "Sales Report"
keyAEKeyForm typeEnumerated formName
keyAEKeyData typeChar "Summary of Sales"
keyAEKeyForm typeEnumerated formAbsolutePosition
keyAEKeyData typeLongInteger 1
Note
The format used in Table 6-7 and similar tables throughout this chapter does not show the structure of nested object specifier records as they exist within an Apple event. Instead, this format shows what you would obtain after calling AEGetKeyDesc repeatedly to extract the object specifier records from an Apple event record.
When you call AEGetKeyDesc to extract a null descriptor record, AEGetKeyDesc returns a descriptor record of type AEDesc with a descriptor type of typeNull and a data handle whose value is 0.u
To specify the default container for an object specifier record (such as the container for the document in Table 6-7), you can use AECreateDesc to create a null descriptor record, which you can then pass in the theContainer parameter of the CreateObjSpecifier function. The CreateObjSpecifier function uses the null descriptor record to create a keyword-specified descriptor record with the keyword keyAEContainer as part of an object specifier record.
The object specifier record that specifies the default container is always the first record you create in a series of nested object specifier records that specifies the complete container hierarchy for an Apple event object. Each one in the series uses the previously created object specifier record to specify its container. As with the null descriptor record, you can pass an object specifier record as the second parameter to the CreateObjSpecifier function, which uses it to create a keyword-specified descriptor record with the keyword keyAEContainer.
To specify the key form for an object specifier record, your application can specify a key form constant as the third parameter to the CreateObjSpecifier function, which uses it to create a keyword-specified descriptor record with the keyword keyAEKeyForm as part of an object specifier record. The standard key forms for object specifier records are summarized in Table 6-1 on page 6-12.
For example, the key form for the object specifier records in Table 6-7 that specify the document and the table is formName. In other words, the key data identifies the document and the table by their names. Similarly, the key form for the object specifier record in Table 6-7 that specifies the first row in the table is formAbsolutePosition. In other words, the key data identifies the position of the row compared to other rows in the same container.
To specify the key data for an object specifier record, your application must create a keyword-specified descriptor record with the keyword keyAEKeyData whose data handle refers to the appropriate data for the specified key form. You can use AECreateDesc, CreateCompDescriptor, CreateLogicalDescriptor, and related functions to create the descriptor record, which you can then pass in the fourth parameter of the CreateObjSpecifier function. The CreateObjSpecifier function uses this descriptor record to create a keyword-specified descriptor record with the keyword keyAEKeyData as part of an object specifier record.
Creating a Simple Object Specifier Record
This section shows how to use the CreateObjSpecifier function to create the object specifier record shown in Table 6-7. The CreateObjSpecifier function creates the necessary keyword-specified descriptor records for the class ID, container, key form, and key data and returns the resulting object specifier record as a descriptor record of type typeObjectSpecifier.
Listing 6-12 shows how the CreateObjSpecifier function creates an object specifier record from parameters that an application specifies.
Listing 6-12 Creating an object specifier record using CreateObjSpecifier
The code shown in Listing 6-12 demonstrates how an application might use the CreateObjSpecifier function to create four keyword-specified descriptor records as part of a descriptor record of type typeObjectSpecifier. The CreateObjSpecifier function returns a result code of noErr if the object specifier record was successfully created. The object specifier record returned in the myObjSpecRec parameter describes an Apple event object of the class specified by the desiredClass parameter, located in the container specified by the myObjectContainer parameter, with the key form specified by the myKeyForm parameter and key data specified by the myKeyDataDesc parameter.
You can specify TRUE in the disposeInputs parameter if you want the CreateObjSpecifier function to dispose of the descriptor records you created for the myObjectContainer and myKeyDataDesc parameters. If you specify FALSE, then your application is responsible for disposing of these leftover descriptor records.
Listing 6-13 shows an application-defined function that uses CreateObjSpecifier to create an object specifier record for the first row in the table named “Summary of Sales” in the document “Sales Report,” then uses the object specifier record returned in the myObjSpecRec parameter as the direct parameter for a Get Data event.
Listing 6-13 Using CreateObjSpecifier in an application-defined function
FUNCTION MyRequestRowFromTarget (targetAddress: AEAddressDesc;
VAR reply: AppleEvent): OSErr;
VAR
desiredClass: DescType;
myKeyForm: DescType;
myObjectContainer: AEDesc;
myObjSpecRec: AEDesc;
myKeyDataDesc: AEDesc;
keyData: LongInt;
theAppleEvent: AppleEvent;
myErr: OSErr;
ignoreErr: OSErr;
BEGIN
{initialize (set to null descriptor records) the two descriptor records }
The MyRequestRowFromTarget function shown in Listing 6-13 specifies the class ID as cRow, indicating that the desired Apple event object is a row in a table. It uses the application-defined function MyCreateTableContainer to create an object specifier record for the table that contains the row, passing “Summary of Sales” and “Sales Report” as the second and third parameters to identify the name of the table and the name of the document that contains the table. (The next section, “Specifying the Container Hierarchy,” explains how to construct the MyCreateTableContainer function.) It then specifies the key form as the constant formAbsolutePosition, which indicates that the key data specifies the position of the row within its container; sets the keyData variable to 1, indicating the first row, and uses AECreateDesc to create a descriptor record for the key data; and uses CreateObjSpecifier to create the object specifier record that describes the desired word.
The desired row is now fully described by the myObjSpecRec variable, which contains a descriptor record of type typeObjectSpecifier that contains the three nested object specifier records shown in Table 6-7 on page 6-56. After using AECreateAppleEvent to create a Get Data event, the MyRequestRowFromTarget function uses the AEPutParamDesc function to add the myObjSpecRec variable to the Get Data event as a direct parameter, then uses AESend to send the Get Data event.
Note that the MyRequestRowFromTarget function begins by using the application-defined function MyInit2DescRecs to set myObjSpecRec and theAppleEvent to null descriptor records. These two functions must be disposed of whether the function is successful or not. By setting them to null descriptor records, the function can dispose of them at the end regardless of where an error may have occurred.
Specifying the Container Hierarchy
Because the container for an object specifier record usually consists of a chain of other object specifier records that specify the container hierarchy, your application must create all the object specifier records in the chain, starting with the record for the outermost container. Listing 6-14 and Listing 6-15 demonstrate how to use the CreateObjSpecifier function to create the first two object specifier records in such a chain: the records for a document and a table.
Listing 6-14 Specifying a document container
FUNCTION MyCreateDocContainer (VAR myDocContainer: AEDesc;
docName: Str255): OSErr;
VAR
myDocDescRec: AEDesc;
nullDescRec: AEDesc;
myErr: OSErr;
BEGIN
{create a descriptor record for the name of the document}
The function MyCreateDocContainer in Listing 6-14 creates an object specifier record that identifies a document by name. It starts by using the AECreateDesc function to create two descriptor records: one of type typeChar for the name of the document, and one of type typeNull for the null descriptor record that specifies the default container (because the document is not contained in any other Apple event object). These two descriptor records can then be used as parameters for the CreateObjSpecifier function, which returns an object specifier record (that is, a descriptor record of type typeObjectSpecifier) in the myDocContainer variable. The object specifier record specifies an Apple event object of the object class cDocument in the container specified by the nullDescRec variable with a key form of formName and the key data specified by the myDocDescRec variable. This object specifier can be used by itself to specify a document, or it can be used to specify the container for another Apple event object.
Listing 6-15 shows an application-defined function, MyCreateTableContainer, that creates an object specifier record describing a table contained in a document.
Listing 6-15 Specifying a table container
FUNCTION MyCreateTableContainer (VAR myTableContainer: AEDesc;
{ first specify the descriptor record for the key data}
myErr := AECreateDesc(typeChar, @tableName[1],
Length(tableName), myTableDescRec);
IF myErr = noErr THEN
myErr := CreateObjSpecifier(cTable, myDocDescRec,
formName, myTableDescRec,
TRUE, myTableContainer);
END;
MyCreateTableContainer := myErr;
END;
The function MyCreateTableContainer in Listing 6-15 starts by using the function MyCreateDocContainer from Listing 6-14 to create an object specifier record that identifies the table’s container—the document in which the table is located. Then it uses the AECreateDesc function to create a descriptor record for the key data—a name that, when combined with the key form formName, will identify the table in the document. The object specifier record for the document and the descriptor record specifying the table’s name are passed to the function CreateObjSpecifier. It returns an object specifier record in the myTableContainer parameter that specifies an Apple event object of the object class cTable in the container specified by the MyDocDescRec variable with a key form of formName and the key data specified by the myTableDescRec variable. This object specifier record can be used by itself to specify a table, or it can be used to specify the container for another Apple event object.
Listing 6-13 uses the MyCreateTableContainer function shown in Listing 6-15 to specify the container hierarchy illustrated in Table 6-7 on page 6-56. The nested object specifier records shown in Table 6-7 use the key forms formName and formRelativePosition. You can create key data for the key forms formPropertyID, formUniqueID, and formRelativePosition using similar techniques.
Specifying a Property
The key form formPropertyID allows your application to specify key data identifying a property of the object specified as a container. For example, an object specifier record that identifies the font property of a word specifies cProperty as the class ID, an object specifier record for the word as the property’s container, formPropertyID as the key form, and the constant pFont as the key data.
Note that an object specifier record that identifies a property does not include a value for the property, such as Palatino. The value of a property is returned or set as a parameter of an Apple event. For example, an application that sends a Get Data event to get the pFont property of a word receives a value such as Palatino in the keyAEResult parameter of the reply event, and an application that sends a Set Data event to change the pFont property of a word specifies a font in the keyAEData parameter of the Set Data event.
To specify the key data for a key form of formPropertyID, your application must create a descriptor record of typeType whose data consists of a constant specifying a property. You can use AECreateDesc to create a descriptor record that specifies the constant for a property, then use CreateObjSpecifier to add the descriptor record to an object specifier record as a keyword-specified descriptor record with the keyword keyAEKeyData.
For more information about object specifier records that specify a property, see “Key Data for a Property ID” on page 6-13.
Specifying a Relative Position
The key form formRelativePosition allows your application to specify key data identifying an element or a set of elements that are immediately before or after the specified container. For example, if the container is a table, you could use a key form of formRelativePosition to specify the paragraph before or after the table.
To specify the key data for a key form of formRelativePosition, your application must create a descriptor record of typeEnumerated whose data consists of a constant specifying either the element after (kAENext) or the element before (kAEPrevious) the specified container.
You can use AECreateDesc to create a descriptor record that specifies one of these constants, then use CreateObjectSpecifier to add it to an object specifier record as a keyword-specified descriptor record with the keyword keyAEKeyData.
For more information about object specifier records that specify a relative position, see “Key Data for Relative Position” on page 6-15.
Creating a Complex Object Specifier Record
This section describes how to create object specifier records that specify a test or a range. You can specify the object class ID for these object specifier records the same way you would for any other object specifier record. When you create the other three keyword-specified descriptor records, however, you can use additional Apple Event Manager routines and descriptor types to specify any combination of Apple event objects.
Specifying a Test
The key form formTest allows your application to specify key data that identifies one or more elements in the specified container that pass a test. To do so, your application must construct several interconnected descriptor records that specify comparisons and, if necessary, logical expressions.
For example, to specify “the first row in which the First Name column equals ‘John’ and the Last Name column equals ‘Chapman’ in the table ‘MyAddresses’ of the database ‘SurfDB,’” your application must construct an object specifier record whose key data describes a logical expression that applies the logical operator AND to two separate comparisons for each row: a comparison of the First Name column to the word “John” and a comparison of the Last Name column to the word “Chapman.”
The logical organization of the data for the object specifier record that specifies this test is summarized in Table 6-8 and Table 6-9. (It is also illustrated in Figure 6-3 and Figure 6-4, beginning on page 6-18.) The listings in the remainder of this section demonstrate how to create this object specifier record. For general information about the organization of key data for a test, see “Key Data for a Test,” which begins on page 6-15.
Table 6-8 Object specifier record for the first row that meets a test in the table named “MyAddresses”
Keyword Descriptor type Data
keyAEDesiredClass typeType cRow
keyAEContainer typeObjectSpecifier (see indented record)
keyAEDesiredClass typeType cRow
keyAEContainer typeObjectSpecifier (see indented record)
keyAEDesiredClass typeType cTable
keyAEContainer typeObjectSpecifier (see indented record)
keyAEDesiredClass typeType cDatabase
keyAEContainer typeNull Data handle is NIL
keyAEKeyForm typeEnumerated formName
keyAEKeyData typeChar "SurfDB"
keyAEKeyForm typeEnumerated formName
keyAEKeyData typeChar "MyAddresses"
keyAEKeyForm typeEnumerated formTest
keyAEKeyData typeLogicalDescriptor (see Table 6-9)
keyAEKeyForm typeEnumerated formAbsolutePosition
keyAEKeyData typeLongInteger 1
Table 6-9 Logical descriptor record that specifies a test
Keyword Descriptor type Data
keyAELogicalOperator typeEnumerated kAEAnd
keyAELogicalTerms typeAEList (see indented records)
typeCompDescriptor (see indented record)
keyAECompOperator typeType kAEEquals
keyAEObject1 typeObjectSpecifier (see indented record)
keyAEDesiredClass typeType cColumn
keyAEContainer typeObjectBeingExamined Data handle is NIL
keyAEKeyForm typeEnumerated formName
keyAEKeyData typeChar "First Name"
keyAEObject2 typeChar "John"
typeCompDescriptor (see indented record)
keyAECompOperator typeType kAEEquals
keyAEObject1 typeObjectSpecifier (see indented record)
keyAEDesiredClass typeType cColumn
keyAEContainer typeObjectBeingExamined Data handle is NIL
keyAEKeyForm typeEnumerated formName
keyAEKeyData typeChar "Last Name"
keyAEObject2 typeChar "Chapman"
Because both the database and the table shown in Table 6-8 are specified by name, it would be convenient to have an application-defined routine that creates an object specifier record that uses the key form formName. The MyCreateFormNameObjSpecifier function shown in Listing 6-16 can be used for this purpose.
Listing 6-16 Creating an object specifier record with the key form formName
The MyCreateFormNameObjSpecifier function shown in Listing 6-16 returns, in the resultObjSpecRec parameter, an object specifier record that describes an Apple event object of the class specified by the class parameter, located in the container specified by the container parameter, with the key form formName and key data specified by the keyDataName parameter. This function is used in Listing 6-19 on page 6-70 to create object specifier records that use the key form formName for the database and the table.
The nested object specifier records shown in Table 6-9 specify “the rows in which the First Name column equals ‘John’ and the Last Name column equals ‘Chapman.’” To identify the rows that pass this test, the Apple Event Manager needs to evaluate two comparisons: the comparison of each row of the First Name column to the word “John,” and the comparison of each row of the Last Name column to the word “Chapman.”
The Apple Event Manager uses the information in comparison descriptor records to compare the specified elements in a container, one at a time, either to another Apple event object or to the data associated with a descriptor record. The two comparison descriptor records you need to create for this example are summarized in Table 6-9 on page 6-66.
You can use the CreateCompDescriptor function to create a comparison descriptor record, or you can create an AE record and use AECoerceDesc to coerce it to a comparison descriptor record. Listing 6-17 shows an example of an application-defined routine that creates an object specifier record and a descriptor record of typeChar, then uses the CreateCompDescriptor function to add them to a comparison descriptor record.
Listing 6-17 Creating a comparison descriptor record
FUNCTION MyCreateComparisonDescRec (VAR compDesc: AEDesc;
colName: str255;
name: str255): OSErr;
VAR
logicalContainer, colNameDesc, nameDesc: AEDesc;
myObjectExaminedContainer: AEDesc;
myErr: OSErr;
BEGIN
{create the object specifier record for keyAEObject1; }
The MyCreateComparisonDescRec function takes two strings and uses them to create a comparison descriptor record. The string passed in the second parameter specifies the name of the column whose contents should be compared to the string passed in the third parameter. First, the MyCreateComparisonDescRec function uses AECreateDesc to create a descriptor record of typeObjectBeingExamined, which is returned in the variable myObjectExaminedContainer. Next, AECreateDesc creates a descriptor record of descriptor type typeChar, whose data consists of the string in the variable colName, and which is returned in the variable colNameDesc. The code then passes the variables myObjectExaminedContainer and colNameDesc to the CreateObjSpecifier function, which uses them to create an object specifier record, returned in the logicalContainer variable, that becomes the keyword-specified descriptor record with the keyword keyAEObject1.
Next, the MyCreateComparisonDescRec function uses AECreateDesc and the name parameter to create the descriptor record for keyAEObject2, which AECreateDesc returns in the nameDesc variable. Finally, the code passes the constant kAEEquals, the variable logicalContainer, and the variable nameDesc to the CreateCompDescriptor function, which creates a comparison descriptor record that allows the Apple Event Manager (with the help of object-comparison functions provided by the server application) to determine whether the specified column in the row currently being checked equals the specified string.
You can use the MyCreateComparisonDescRec function to create both the descriptor records of type typeCompDescriptor shown in Table 6-9 on page 6-66. These descriptor records provide two logical terms for a logical descriptor record. The entire logical descriptor record corresponds to the logical expression “the First Name column equals ‘John’ AND the Last Name column equals ‘Chapman.’”
You can use the CreateLogicalDescriptor function to create a logical descriptor record, or you can create an AE record and use the AECoerceDesc function to coerce it to a comparison descriptor record. Listing 6-18 shows an application-defined function that adds two comparison descriptor records to a descriptor list, then uses the CreateLogicalDescriptor function to create a logical descriptor record whose logical terms are the two comparison descriptor records.
Listing 6-18 Creating a logical descriptor record
FUNCTION MyCreateLogicalDescRec (VAR compDesc1, compDesc2: AEDesc;
logicalOperator: DescType;
VAR logicalDesc: AEDesc): OSErr;
VAR
logicalTermsList: AEDescList;
myErr: OSErr;
BEGIN
{create a logical descriptor record that contains two }
Listing 6-19 uses the application-defined functions shown in Listing 6-16, Listing 6-17, and Listing 6-18 to build the object specifier record illustrated in Table 6-8 and Table 6-9.
Listing 6-19 Creating a complex object specifier record
FUNCTION MyCreateObjSpecRec (VAR theResultObj: AEDesc): OSErr;
The MyCreateObjSpecRec function shown in Listing 6-19 begins by using AECreateDesc to create a null descriptor record, then uses the MyCreateFormNameObjSpecifier function (shown in Listing 6-16) to specify the default container for the database named “SurfDB.” The code then calls the MyCreateFormNameObjSpecifier function again, this time passing the object specifier record for SurfDB to specify the container for the table “MyAddresses.” The next two calls are both to the MyCreateComparisonDescRec function (shown in Listing 6-17), which creates the comparison descriptor records that allow the Apple Event Manager to compare the First Name column and Last Name column to the names “John” and “Chapman,” respectively. The next call passes these two comparison descriptor records to the MyCreateLogicalDescRec function (shown in Listing 6-18) in the compDesc1 and compDesc2 variables.
Now all the components of the logical descriptor record are ready to assemble. The next call, to CreateObjSpecifier, specifies the logical descriptor record in the logicalTestDesc variable as the key data for the object specifier record that specifies the test. A call to the Apple Event Manager routine CreateOffsetDescriptor then creates an offset descriptor record that contains the integer 1. Finally, the code passes the offset descriptor record to the CreateObjSpecifier function in the rowOffset variable to create the final object specifier record, which describes the requested row as the first row that passes the test.
The CreateOffsetDescriptor function creates a descriptor record of type typeLongInteger that can be used as the key data with a key form of formAbsolutePosition to indicate an element’s offset within its container. A positive integer indicates an offset from the beginning of the container (the first element has an offset of 1), and a negative integer indicates an offset from the end of the container (the last element has an offset of –1). Using CreateOffsetDescriptor accomplishes the same thing as setting a variable to an integer and passing the variable to AECreateDesc to create a descriptor record of type typeLongInteger.
Specifying a Range
The key form formRange allows your application to specify key data that identifies a range of elements in the specified container. To do so, your application must first create a range descriptor record. The Apple Event Manager uses a range descriptor record to identify the two Apple event objects that specify the beginning and end of a range of elements.
For example, an object specifier record for a range of text in a document could specify the table named “Summary of Sales” as the first boundary object and the figure named “Best-Selling Widgets for 1991” as the second boundary object for a range that consists of all the text between the table and the figure. Any word processor that keeps track of the relative positions of text, tables, and figures should be capable of supporting such a request.
Table 6-10 summarizes the logical organization of the data for the object specifier record that specifies this range. For general information about the organization of data within a range descriptor record, see “Key Data for a Range” on page 6-20.
Table 6-10 A range descriptor record
Keyword Descriptor type Data
keyAERangeStart typeObjectSpecifier (see indented record)
keyAEDesiredClass typeType cTable
keyAEContainer typeCurrentContainer Data handle is NIL
keyAEKeyForm typeEnumerated formName
keyAEKeyData typeChar "Summary of Sales"
keyAERangeStop typeObjectSpecifier (see indented record)
keyAEDesiredClass typeType cFigure
keyAEContainer typeCurrentContainer Data handle is NIL
keyAEKeyForm typeEnumerated formName
keyAEKeyData typeChar "Best-Selling Widgets
for 1991"
You can use the CreateRangeDescriptor function to create a range descriptor record, or you can create an AE record and use AECoerceDesc to coerce it to a range descriptor record. Listing 6-20 provides an example of an application-defined routine that creates two object specifier records, then uses the CreateRangeDescriptor function to add them to a range descriptor record.
The container for the boundary objects in the range descriptor record created by
Listing 6-20 is the same as the container for the range itself. The object specifier record for the range’s container is added to an object specifier record of key form formRange at the same time that the range descriptor record is added as key data. The container for the two boundary objects can therefore be specified in the range descriptor record by a descriptor record of type typeCurrentContainer whose data handle has the value NIL. The Apple Event Manager interprets this as a placeholder for the range’s container when it is resolving the range descriptor record.
Listing 6-20 Creating a range descriptor record
FUNCTION MyCreateRangeDescriptor (VAR rangeDescRec: AEDesc): OSErr;
VAR
rangeStart: AEDesc;
rangeEnd: AEDesc;
currentContainer: AEDesc;
tableNameDescRec : AEDesc;
figureNameDescRec : AEDesc;
myErr: OSErr;
BEGIN
{create the object specifier record for the start of the range }
{ (the table named 'Summary of Sales' in 'MyDoc' document)}
{create a descriptor record of type typeCurrentContainer}
After creating a descriptor record of type typeCurrentContainer and a descriptor record for the first table’s name, Listing 6-20 uses the CreateObjSpecifier function to create an object specifier record that identifies the beginning of the range. The parameters to CreateObjSpecifier specify that the beginning of the range is an Apple event object of the object class cTable in the current container, with a key form of formName and key data that identifies the table by name. A second call to CreateObjSpecifier creates the object specifier record that identifies the end of the range—an Apple event object of the cFigure object class in the current container, with a key form of formName and key data that identifies the figure by name. Finally, the code in Listing 6-20 uses the CreateRangeDescriptor function to create the range descriptor record, using the two previously created object specifier records to specify the beginning and end of the range.
Reference to Resolving and Creating Object Specifier Records
This section describes the Apple Event Manager routines your application can use to resolve and create object specifier records. It also describes application-defined object accessor functions and object callback functions that your application can provide for use by the Apple Event Manager in resolving object specifier records.
The first section, “Data Structures Used in Object Specifier Records,” summarizes the descriptor types and associated data that can be used in an object specifier record. “Routines for Resolving and Creating Object Specifier Records,” which begins on page 6-77, describes the Apple Event Manager routines you use to initialize the Object Support Library, resolve object specifier records, set and manipulate object accessor functions, deallocate memory for tokens, and create object specifier records. “Application-Defined Routines,” which begins on page 6-94, describes the object accessor functions and object callback functions that a server application can provide.
Data Structures Used in Object Specifier Records
The data for object specifier records can be specified using a variety of descriptor records and descriptor types. These are described in detail in “Descriptor Records Used in Object Specifier Records,” which begins on page 6-8, and summarized in Table 6-11.
Table 6-11 Keyword-specified descriptor records for typeObjectSpecifier(continued)(continued)
Keyword Descriptor type Data
keyAEDesiredClass typeType Object class ID
keyAEContainer typeObjectSpecifier Object specifier record
typeNull Data handle is NIL. Specifies the default container at the top of the container hierarchy.
typeObjectBeingExamined Data handle is NIL. Specifies the container for elements that are tested one at a time; used only with formTest.
typeCurrentContainer Data handle is NIL. Specifies a container for an element that demarcates one boundary in a range. Used only with formRange.
keyAEKeyForm typeEnumerated formPropertyID
formName
formUniqueID
formAbsolutePosition
formRelativePosition
formTest
formRange
formWhose
keyAEKeyData (See indented key forms)
for formPropertyID typeType Property ID for an element’s property
for formName typeChar or other text type Element’s name
for formUniqueID Any appropriate type Element’s unique ID
for formAbsolutePosition typeLongInteger Offset from beginning (positive) or end (negative) of container
typeAbsoluteOrdinal kAEFirst
kAEMiddle
kAELast
kAEAny
kAEAll
for formRelativePosition typeEnumerated kAENext
kAEPrevious
for formTest typeCompDescriptor (See Table 6-2 on page 6-16)
typeLogicalDescriptor (See Table 6-3 on page 6-17)
for formRange typeRangeDescriptor (See Table 6-4 on page 6-20)
for formWhose typeWhoseDescriptor (See Table 6-5 on page 6-42)
Routines for Resolving and Creating Object Specifier Records
This section describes routines for initializing the Object Support Library, resolving object specifier records, setting and manipulating object accessor functions, deallocating memory for tokens, and creating object specifier records.
Initializing the Object Support Library
You should call the AEObjectInit function to initialize the Apple Event Manager routines that handle object specifier records and Apple event objects. To make these routines available to your application with version 1.01 and earlier versions of the Apple Event Manager, you must also link the Apple Event Object Support Library with your application when you build it.
AEObjectInit
You use the AEObjectInit function to initialize the Object Support Library.
FUNCTION AEObjectInit: OSErr;
DESCRIPTION
You must call this function before calling any of the Apple Event Manager routines that describe or manipulate Apple event objects.
RESULT CODESnoErr 0 No error occurred
memFullErr –108 Not enough room in heap zone
errAENewerVersion –1706 Need a newer version of the Apple Event Manager
Setting Object Accessor Functions and Object Callback Functions
The Apple Event Manager provides two routines that allow you to specify the object accessor functions and object callback functions provided by your application. The AEInstallObjectAccessor function adds an entry for an object accessor function to either the application’s object accessor dispatch table or the system object accessor dispatch table. The AESetObjectCallbacks function allows you to specify the object callback functions to be called for your application.
AEInstallObjectAccessor
You can use the AEInstallObjectAccessor function to add an entry for an object accessor function to either the application’s object accessor dispatch table or the system object accessor dispatch table.
FUNCTION AEInstallObjectAccessor (desiredClass: DescType;
containerType: DescType;
theAccessor: AccessorProcPtr;
accessorRefcon: LongInt;
isSysHandler: Boolean): OSErr;
desiredClass
The object class of the Apple event objects to be located by the object accessor function for this table entry.
containerType
The descriptor type of the token used to specify the container for the desired objects. The object accessor function finds objects in containers specified by tokens of this type.
theAccessor
A pointer to the object accessor function for this table entry. Note that an object accessor function listed in the system dispatch table must reside in the system heap; thus, if the value of the isSysHandler parameter is TRUE, the theAccessor parameter should point to a location in the system heap. Otherwise, if you put your system object accessor function in your application heap, you must call AERemoveObjectAccessor to remove the function before your application terminates.
accessorRefcon
A reference constant passed by the Apple Event Manager to the object accessor function whenever the function is called. If your object accessor function doesn’t use a reference constant, use 0 as the value of this parameter. To change the value of the reference constant, you must call AEInstallObjectAccessor again.
isSysHandler
A value that specifies the object accessor dispatch table to which the entry is added. If the value of isSysHandler is TRUE, the Apple Event Manager adds the entry to the system object accessor dispatch table. Entries in the system object accessor dispatch table are available to all applications running on the same computer. If the value is FALSE, the Apple Event Manager adds the entry to your application’s object accessor table. When searching for object accessor functions, the Apple Event Manager searches the application’s object accessor dispatch table first; it searches the system object accessor dispatch table only if the necessary function is not found in your application’s object accessor dispatch table.
DESCRIPTION
The AEInstallObjectAccessor function adds an entry to either the application or system object accessor dispatch table. You must supply parameters that specify the object class of the Apple event objects that the object accessor function can locate, the descriptor type of tokens for containers in which the object accessor function can locate objects, the address of the object accessor function for which you are adding an entry, and whether the entry is to be added to the system object accessor dispatch table or your application’s object accessor dispatch table. You can also specify a reference constant that the Apple Event Manager passes to your object accessor function each time the Apple Event Manager calls the function.
RESULT CODESnoErr 0 No error occurred
paramErr –50 The handler pointer is NIL or odd, or AEObjectInit was not called before this function
SEE ALSO
For more information about installing object accessor functions, see “Installing Entries in the Object Accessor Dispatch Tables,” which begins on page 6-21.
For a description of the AERemoveObjectAccessor function, see page 6-84.
AESetObjectCallbacks
You can use the AESetObjectCallbacks function to specify the object callback functions to be called for your application.
FUNCTION AESetObjectCallbacks (myCompareProc, myCountProc,
myDisposeTokenProc,
myGetMarkTokenProc, myMarkProc,
myAdjustMarksProc,
myGetErrDescProc: ProcPtr): OSErr;
myCompareProc
Either a pointer to the object-comparison function provided by your application or NIL if no function is provided.
myCountProc
Either a pointer to the object-counting function provided by your application or NIL if no function is provided.
myDisposeTokenProc
Either a pointer to the token disposal function provided by your application or NIL if no function is provided.
myGetMarkTokenProc
Either a pointer to the function for returning a mark token provided by your application or NIL if no function is provided.
myMarkProc Either a pointer to the object-marking function provided by your application or NIL if no function is provided.
myAdjustMarksProc
Either a pointer to the mark-adjusting function provided by your application or NIL if no function is provided.
myGetErrDescProc
Either a pointer to the error callback function provided by your application or NIL if no function is provided.
DESCRIPTION
Your application can provide only one each of the object callback functions specified by AESetObjectCallbacks: one object-comparison function, one object-counting function, and so on. As a result, each of these callback functions must perform the requested task (comparing, counting, and so on) for all the object classes that your application supports. In contrast, your application may provide many different object accessor functions if necessary, depending on the object classes and token types your application supports.
To replace object callback routines that have been previously installed, you can make another call to AESetObjectCallbacks. Each additional call to AESetObjectCallbacks replaces any object callback functions installed by previous calls to AESetObjectCallbacks. You cannot use AESetObjectCallbacks to replace system object callback routines or object accessor functions. Only those routines you specify are replaced; to avoid replacing existing callback functions, specify a value of NIL for the functions you don’t want to replace.
RESULT CODESnoErr 0 No error occurred
paramErr –50 The handler pointer is NIL or odd, or AEObjectInit was not called before this function
memFullErr –108 There is not enough room in heap zone
errAENotASpecialFunction –1714 The keyword is not valid for a special function
SEE ALSO
For information about writing object callback functions, see “Application-Defined Routines,” which begins on page 6-94.
To install system object callback functions, use the AEInstallSpecialHandler function described on page 4-100.
Getting, Calling, and Removing Object Accessor Functions
The Apple Event Manager provides three functions that allow you to get, call, and remove object accessor functions that you have installed in either the system or application object accessor dispatch table with the AEInstallObjectAccessor function. The AEGetObjectAccessor and AECallObjectAccessor functions get and call object accessor functions installed in the dispatch table you specify, and AERemoveObjectAccessor removes an installed function.
AEGetObjectAccessor
You can use the AEGetObjectAccessor function to get a pointer to an object accessor function and the value of its reference constant.
FUNCTION AEGetObjectAccessor (desiredClass: DescType;
containerType: DescType;
VAR theAccessor: AccessorProcPtr;
VAR accessorRefcon: LongInt;
isSysHandler: Boolean): OSErr;
desiredClass
The object class of the Apple event objects located by the requested object accessor function. This parameter can also contain the constant typeWildCard or the constant cProperty.
containerType
The descriptor type of the token that identifies the container for the objects located by the requested object accessor function. This parameter can also contain the constant typeWildCard.
theAccessor
The AEGetObjectAccessor function returns a pointer to the requested object accessor function in this parameter.
accessorRefcon
The AEGetObjectAccessor function returns the reference constant from the object accessor dispatch table entry for the specified object accessor function in this parameter.
isSysHandler
A value that specifies the object accessor table from which to get the object accessor function and its reference constant. If the value of isSysHandler is TRUE, AEGetObjectAccessor gets the function from the system object accessor dispatch table. If the value of isSysHandler is FALSE, AEGetObjectAccessor gets the function from the application’s object accessor dispatch table.
DESCRIPTION
The AEGetObjectAccessor function returns a pointer to the object accessor function installed for the object class specified in the desiredClass parameter and the descriptor type specified in the containerType parameter. It also returns the reference constant associated with the specified function. You must supply a value in the isSysHandler parameter that specifies which object accessor dispatch table you want to get the function from.
Calling AEGetObjectAccessor does not remove the object accessor function from an object accessor dispatch table.
To get an object accessor function whose entry in an object accessor dispatch table specifies typeWildCard as the object class, you must specify typeWildCard as the value of the desiredClass parameter. Similarly, to get an object accessor function whose entry in an object accessor dispatch table specifies typeWildCard as the descriptor type of the token used to specify the container, you must specify typeWildCard as the value of the containerType parameter.
To get an object accessor function whose entry in an object accessor dispatch table specifies cProperty (a constant used to specify a property of any object class), you must specify cProperty as the desiredClass parameter.
RESULT CODESnoErr 0 No error occurred
paramErr –50 AEObjectInit was not called before this function was called
errAEAccessorNotFound –1723 There is no object accessor function for the specified object class and container type
AECallObjectAccessor
You can use the AECallObjectAccessor function to invoke one of your application’s object accessor functions.
FUNCTION AECallObjectAccessor (desiredClass: DescType;
containerToken: AEDesc;
containerClass: DescType;
keyForm: DescType;
keyData: AEDesc;
VAR theToken: AEDesc): OSErr;
desiredClass
The object class of the desired Apple event objects.
containerToken
The token that identifies the container for the desired objects.
containerClass
The object class of the container for the desired objects.
keyForm The key form specified by the object specifier record for the object or objects to be located.
keyData The key data specified by the object specifier record for the object or objects to be located.
theToken The object accessor function that is invoked returns a token specifying the desired object or objects in this parameter.
DESCRIPTION
If you want your application to do some of the Apple event object resolution normally performed by the AEResolve function, you can use AECallObjectAccessor to invoke an object accessor function. This might be useful, for example, if you have installed an object accessor function using typeWildCard for the AEInstallObjectAccessor function’s desiredClass parameter and typeAEList for the containerType parameter. To return a list of tokens for a request like “every line that ends in a period,” the object accessor function can create an empty list, then call AECallObjectAccessor for each requested element, adding tokens for each element to the list one at a time.
The parameters of AECallObjectAccessor are identical to the parameters of an object accessor function, with one exception: the parameter that specifies the reference constant passed to the object accessor function whenever it is called is added by the Apple Event Manager when it calls the object accessor function.
To call an object accessor function whose entry in an object accessor dispatch table specifies typeWildCard as the object class, you must specify typeWildCard as the value of the desiredClass parameter.
To call an object accessor function whose entry in an object accessor dispatch table specifies cProperty, you must specify cProperty as the desiredClass parameter.
RESULT CODES
In addition to the following result codes, AECallObjectAccessor returns any other result codes returned by the object accessor function that is called.noErr 0 No error occurred
paramErr –50 AEObjectInit was not called before this function was called
errAEAccessorNotFound –1723 No object accessor was found
AERemoveObjectAccessor
You can use the AERemoveObjectAccessor function to remove an object accessor function from an object accessor dispatch table.
FUNCTION AERemoveObjectAccessor (desiredClass: DescType;
containerType: DescType;
theAccessor: AccessorProcPtr;
isSysHandler: Boolean): OSErr;
desiredClass
The object class of the Apple event objects located by the object accessor function. The desiredClass parameter can also contain the constant typeWildCard or the constant cProperty.
containerType
The descriptor type of the token that identifies the container for the objects located by the object accessor function. The containerType parameter can also contain the constant typeWildCard.
theAccessor
A pointer to the object accessor function you want to remove. Although the parameters desiredClass and containerType would be sufficient to identify the function to be removed, providing the parameter theAccessor guarantees that you remove the correct function. If this parameter does not contain a pointer to the object accessor function you want to remove, its value should be NIL.
isSysHandler
A value that specifies the object accessor dispatch table from which to remove the object accessor function. If the value of isSysHandler is TRUE, AEGetObjectAccessor removes the routine from the system object accessor dispatch table. If the value is FALSE, AEGetObjectAccessor removes the routine from the application object accessor dispatch table.
DESCRIPTION
The AERemoveObjectAccessor function removes the object accessor function you have installed for the object class specified in the desiredClass parameter and the descriptor type specified in the containerType parameter.
To remove an object accessor function whose entry in an object accessor dispatch table specifies typeWildCard as the object class, you must specify typeWildCard as the value of the desiredClass parameter. Similarly, to remove an object accessor function whose entry in an object accessor dispatch table specifies typeWildCard as the descriptor type of the token used to specify the container for the desired objects, you must specify typeWildCard as the value of the containerType parameter.
To remove an object accessor function whose entry in an object accessor dispatch table specifies cProperty (a constant used to specify a property of any object class), you must specify cProperty as the desiredClass parameter.
RESULT CODESnoErr 0 No error occurred
paramErr –50 AEObjectInit was not called before this function was called
errAEAccessorNotFound –1723 There is no object accessor function for the specified object class and container type
Resolving Object Specifier Records
If an Apple event parameter consists of an object specifier record, your handler for the event typically calls the AEResolve function to begin the process of resolving the object specifier record.
AEResolve
You can use the AEResolve function to resolve an object specifier record in an Apple event parameter.
FUNCTION AEResolve (objectSpecifier: AEDesc;
callbackFlags: Integer;
VAR theToken: AEDesc): OSErr;
objectSpecifier
The object specifier record to be resolved.
callbackFlags
A value that determines what additional assistance, if any, your application can give the Apple Event Manager when it parses the object specifier record. The value is specified by adding the following constants, as appropriate:
CONST kAEIDoMinimum = $0000; {supports minimum }
{ callbacks only}
kAEIDoWhose = $0001; {supports formWhose}
kAEIDoMarking = $0004; {provides marking }
{ functions}
theToken The AEResolve function returns, in this parameter, a token that identifies the Apple event objects specified by the objectSpecifier parameter. Your object accessor functions may need to create many tokens to resolve a single object specifier record; this parameter contains only the final token that identifies the requested Apple event object. If an error occurs, AEResolve returns a null descriptor record.
DESCRIPTION
The AEResolve function resolves the object specifier record passed in the objectSpecifier parameter with the help of the object accessor functions and object callback functions provided by your application.
RESULT CODESnoErr 0 No error occurred
paramErr –50 AEObjectInit was not called before this function was called
errAEHandlerNotFound –1717 The necessary object callback function was not found (this result is returned only for object callback functions; errAEAccessorNotFound [–1723] is returned when an object accessor function is not found)
errAEImpossibleRange –1720 The range is not valid because it is impossible for a range to include the first and last objects that were specified; an example is a range in which the offset of the first object is greater than the offset of the last object
errAEWrongNumberArgs –1721 The number of operands provided for the kAENOT logical operator is not 1
errAEAccessorNotFound –1723 There is no object accessor function for the specified object class and token descriptor type
errAENoSuchLogical –1725 The logical operator in a logical descriptor record is not kAEAND, kAEOR, or kAENOT
errAEBadTestKey –1726 The descriptor record in a test key is neither a comparison descriptor record nor a logical descriptor record
errAENotAnObjectSpec –1727 The objSpecifier parameter of AEResolve is not an object specifier record
errAENegativeCount –1729 An object-counting function returned a negative result
errAEEmptyListContainer –1730 The container for an Apple event object is specified by an empty list
In addition to the result codes listed here, AEResolve also returns any result code returned by one of your application’s object accessor functions or object callback functions. For example, an object accessor function can return errAENoSuchObject (–1728) when it can’t find an Apple event object, or it can return more specific result codes.
If any object accessor function or object callback function returns a result code other than noErr or errAEEventNotHandled, AEResolve immediately disposes of any existing tokens and returns. The result code it returns in this case is the result code returned by the object accessor function or the object callback function.
SEE ALSO
For an overview of the way AEResolve works with object accessor functions, see “Resolving Object Specifier Records,” which begins on page 6-4.
Deallocating Memory for Tokens
Whenever the AEResolve function returns a final token to your event handler as the result of the resolution of an object specifier record passed to AEResolve, your application can call the AEDisposeToken function to deallocate the memory used by the token.
AEDisposeToken
You can use the AEDisposeToken function to deallocate the memory used by a token.
FUNCTION AEDisposeToken (VAR theToken: AEDesc): OSErr;
theToken The token to be disposed of.
DESCRIPTION
When your application calls the AEDisposeToken function, the Apple Event Manager first calls your application’s token disposal function, if you have provided one. If you haven’t provided a token disposal function, or if your application’s token disposal function returns errAEEventNotHandled as the function result, the Apple Event Manager calls the system token disposal function if one is available. If there is no system token disposal function or the function returns errAEEventNotHandled as the function result, the Apple Event Manager calls the AEDisposeDesc function to dispose of the token.
RESULT CODES
In addition to the following result codes, AEDisposeToken also returns result codes returned by the token disposal function that disposed of the token.noErr 0 No error occurred
paramErr –50 AEObjectInit was not called before this function was called
notASpecialFunction –1714 The keyword is not valid for a special function
SEE ALSO
For information about writing a token disposal function, see page 6-99.
Creating Object Specifier Records
The Apple Event Manager provides five functions that you can use to create some of the components of an object specifier record or to assemble an object specifier record:
n The CreateOffsetDescriptor function creates an offset descriptor record, which specifies the position of an element in relation to the beginning or end of its container.
n The CreateCompDescriptor function creates a comparison descriptor record, which specifies how to compare one or more Apple event objects with either another Apple event object or a descriptor record.
n The CreateLogicalDescriptor function creates a logical descriptor record, which specifies a logical operator and one or more logical terms for the Apple Event Manager to evaluate.
n The CreateRangeDescriptor function creates a range descriptor record, which specifies a series of consecutive elements in the same container.
n The CreateObjSpecifier function assembles an object specifier record, which identifies one or more Apple event objects, from other descriptor records.
Instead of using these functions, you can create the corresponding descriptor records yourself using the AECreateDesc function, add them to an AE record using other Apple Event Manager routines, and coerce the AE record to a descriptor record of type typeObjectSpecifier. However, in most cases it is easier to use the functions listed in this section.
All of these functions except for CreateOffsetDescriptor include a disposeInputs parameter. If the value of this parameter is TRUE, the function automatically disposes of any descriptor records you have provided as parameters to the function. If the value is FALSE, the application must dispose of the records itself. A value of FALSE may be more efficient for some applications because it allows them to reuse descriptor records.
For more information about these functions and examples of their use, see “Creating Object Specifier Records,” which begins on page 6-55.
CreateOffsetDescriptor
You can use the CreateOffsetDescriptor function to create an offset descriptor record.
FUNCTION CreateOffsetDescriptor (theOffset: LongInt;
VAR theDescriptor: AEDesc)
: OSErr;
theOffset A positive integer that specifies the offset from the beginning of the container (the first element has an offset of 1), or a negative integer that specifies the offset from the end (the last element has an offset of –1).
theDescriptor
The offset descriptor record created by CreateOffsetDescriptor.
DESCRIPTION
The CreateOffsetDescriptor function creates an offset descriptor record that specifies the position of an element in relation to the beginning or end of its container.
RESULT CODESnoErr 0 No error occurred
memFullErr –108 Not enough room in heap zone
CreateCompDescriptor
You can use the CreateCompDescriptor function to create a comparison descriptor record.
FUNCTION CreateCompDescriptor (comparisonOperator: DescType;
VAR operand1: AEDesc;
VAR operand2: AEDesc;
disposeInputs: Boolean;
VAR theDescriptor: AEDesc)
: OSErr;
comparisonOperator
The comparison operator for comparing the descriptor records in the operand1 and operand2 parameters. The operator is specified by the constants listed in the description that follows.
operand1 An object specifier record.
operand2 A descriptor record (which can be an object specifier record or any other descriptor record) whose value is to be compared to the value of operand1.
disposeInputs
A Boolean value indicating whether the function (TRUE) or your application (FALSE) should dispose of the descriptor records for the two operands.
theDescriptor
The comparison descriptor record created by CreateCompDescriptor.
DESCRIPTION
The CreateCompDescriptor function creates a comparison descriptor record, which specifies how to compare one or more Apple event objects with either another Apple event object or a descriptor record.
The actual comparison of the two operands is performed by the object-comparison function provided by the client application. The way a comparison operator is interpreted is up to each application.
These are the currently defined standard comparison operators:
Constant Meaning
kAEGreaterThan The value of operand1 is greater than the value of operand2.
kAEGreaterThanEquals The value of operand1 is greater than or equal to the value of operand2.
kAEEquals The value of operand1 is equal to the value of operand2.
kAELessThan The value of operand1 is less than the value of operand2.
kAELessThanEquals The value of operand1 is less than or equal to the value of operand2.
kAEBeginsWith The value of operand1 begins with the value of operand2 (for example, the string "operand" begins with the string "opera").
kAEEndsWith The value of operand1 ends with the value of operand2 (for example, the string "operand" ends with the string "and").
kAEContains The value of operand1 contains the value of operand2 (for example, the string "operand" contains the string "era").
RESULT CODESnoErr 0 No error occurred
paramErr –50 Error in parameter list
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested Apple event data type
errAEWrongDataType –1703 Wrong Apple event data type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
SEE ALSO
For an example of how to use the CreateCompDescriptor function to create a comparison descriptor record, see “Specifying a Test,” which begins on page 6-64.
CreateLogicalDescriptor
You can use the CreateLogicalDescriptor function to create a logical descriptor record.
FUNCTION CreateLogicalDescriptor
(VAR theLogicalTerms: AEDescList;
theLogicOperator: DescType;
disposeInputs: Boolean;
VAR theDescriptor: AEDesc): OSErr;
theLogicalTerms
A list containing comparison descriptor records, logical descriptor records, or both. If the value of the parameter theLogicOperator is kAEAND or kAEOR, the list can contain any number of descriptors. If the value of the parameter theLogicOperator is kAENOT, logically this list should contain a single descriptor record. However, the function will not return an error if the list contains more than one descriptor record for a logical operator of kAENOT.
theLogicOperator
A logical operator represented by one of the following constants:
CONST kAEAND = 'AND ';
kAEOR = 'OR ';
kAENOT = 'NOT ';
disposeInputs
A Boolean value indicating whether the function (TRUE) or your application (FALSE) should dispose of the descriptor records in the other parameters.
theDescriptor
The logical descriptor record created by CreateLogicalDescriptor.
DESCRIPTION
The CreateLogicalDescriptor function creates a logical descriptor record, which specifies a logical operator and one or more logical terms for the Apple Event Manager to evaluate.
RESULT CODESnoErr 0 No error occurred
paramErr –50 Error in parameter list
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to requested Apple event data type
errAEWrongDataType –1703 Wrong Apple event data type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
SEE ALSO
For an example of how to use the CreateLogicalDescriptor function to create a logical descriptor record, see “Specifying a Test,” which begins on page 6-64.
CreateRangeDescriptor
You can use the CreateRangeDescriptor function to create a range descriptor record.
FUNCTION CreateRangeDescriptor (VAR rangeStart: AEDesc;
VAR rangeStop: AEDesc;
disposeInputs: Boolean;
VAR theDescriptor: AEDesc): OSErr;
rangeStart
An object specifier record that identifies the first Apple event object in the range.
rangeStop An object specifier record that identifies the last Apple event object in the range.
disposeInputs
A Boolean value indicating whether the function (TRUE) or your application (FALSE) should dispose of the descriptor records for the rangeStart and rangeStop parameters.
theDescriptor
The range descriptor record created by CreateRangeDescriptor.
DESCRIPTION
The CreateRangeDescriptor function creates a range descriptor record, which specifies a series of consecutive elements in the same container. Although the rangeStart and rangeStop parameters can be any object specifier records—including object specifier records that specify more than one Apple event object—most applications expect these parameters to specify single Apple event objects.
RESULT CODESnoErr 0 No error occurred
paramErr –50 Error in parameter list
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested Apple event data type
errAEWrongDataType –1703 Wrong Apple event data type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
SEE ALSO
For an example of how to use the CreateRangeDescriptor function to create a range descriptor record, see “Specifying a Range” on page 6-72.
CreateObjSpecifier
You can use the CreateObjSpecifier function to create an object specifier record.
FUNCTION CreateObjSpecifier (desiredClass: DescType;
VAR theContainer: AEDesc;
keyForm: DescType;
VAR keyData: AEDesc;
disposeInputs: Boolean;
VAR objSpecifier: AEDesc): OSErr;
desiredClass
The object class of the desired Apple event objects.
theContainer
A description of the container for the requested object, usually in the form of another object specifier record.
keyForm The key form for the object specifier record.
keyData The key data for the object specifier record.
disposeInputs
A Boolean value indicating whether the function (TRUE) or your application (FALSE) should dispose of the descriptor records for the other parameters.
objSpecifier
The object specifier record created by the CreateObjSpecifier function.
DESCRIPTION
The CreateObjSpecifier function assembles an object specifier record from the specified constants and other descriptor records.
RESULT CODESnoErr 0 No error occurred
paramErr –50 Error in parameter list
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested Apple event data type
errAEWrongDataType –1703 Wrong Apple event data type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
SEE ALSO
For information about how to assemble the components of an object specifier record with the CreateObjSpecifier function, see “Creating Object Specifier Records,” which begins on page 6-55.
Application-Defined Routines
The AEResolve function performs tasks that are required to resolve any object specifier record, such as parsing its contents, keeping track of the results of tests, and handling memory management. When necessary, AEResolve calls application-defined functions to perform tasks that are unique to the application, such as locating a specific Apple event object in the application’s data structures or counting the number of Apple event objects in a container.
AEResolve can call two kinds of application-defined functions:
n Object accessor functions locate Apple event objects. Every application that supports simple object specifier records must provide one or more object accessor functions.
n Object callback functions perform other tasks that only an application can perform, such as counting, comparing, or marking Apple event objects. You can provide up to seven object callback functions, depending on the needs of your application.
This section provides model declarations for the object accessor functions and object callback functions that your application can provide.
Object Accessor Functions
You must provide one or more object accessor functions that can locate all the element classes and properties listed in the Apple Event Registry: Standard Suites for the object classes supported by your application. This section provides the routine declaration for an object accessor function.
MyObjectAccessor
Object accessor functions locate Apple event objects of a specified object class in a container identified by a token of a specified descriptor type.
FUNCTION MyObjectAccessor (desiredClass: DescType;
containerToken: AEDesc;
containerClass: DescType;
keyForm: DescType; keyData: AEDesc;
VAR theToken: AEDesc;
theRefcon: LongInt): OSErr;
desiredClass
The object class of the desired Apple event objects.
containerToken
A token that specifies the container of the desired Apple event objects.
containerClass
The object class of the container.
keyForm The key form specified by the object specifier record being resolved.
keyData The key data specified by the object specifier record being resolved.
theToken The token returned by the MyObjectAccessor function.
theRefcon A reference constant that the Apple Event Manager passes to the object accessor function each time it is called.
DESCRIPTION
Each object accessor function provided by your application should either find elements of a specified object class or find properties of an Apple event object. The AEResolve function uses the object class ID of the specified Apple event object and the descriptor type of the token that identifies the object’s container to determine which object accessor function to call. To install an object accessor function either in your application’s object accessor dispatch table or in the system object accessor dispatch table, use the AEInstallObjectAccessor function, which is described on page 6-78.
SPECIAL CONSIDERATIONS
If the Apple Event Manager receives the result code errAEEventNotHandled after calling an object accessor function, it attempts to use other methods of locating the requested objects, such as calling an equivalent system object accessor function. Thus, an object accessor function that can’t locate a requested object should return errAEEventNotHandled. This allows the Apple Event Manager to try other object accessor functions that may be available.
RESULT CODESnoErr 0 No error occurred
errAEEventNotHandled –1708 The object accessor function is unable to locate the requested Apple event object or objects
SEE ALSO
For information about installing object accessor functions, see “Installing Entries in the Object Accessor Dispatch Tables,” which begins on page 6-21.
For information about writing object accessor functions, see “Writing Object Accessor Functions,” which begins on page 6-28.
Object Callback Functions
If an Apple event parameter consists of an object specifier record, your handler for the Apple event typically calls AEResolve to begin the process of locating the requested Apple event objects. The AEResolve function in turn calls object accessor functions and, if necessary, object callback functions provided by your application when it needs the information they can provide.
This section provides declarations for the seven object callback functions that your application can provide: the object-counting function (MyCountObjects), object-comparison function (MyCompareObjects), token disposal function (MyDisposeToken), error callback function (MyGetErrorDesc), mark token function (MyGetMarkToken), object-marking function (MyMark), and mark-adjusting function (MyAdjustMarks).
For information about writing and installing object callback functions, see “Writing Object Callback Functions,” which begins on page 6-45.
MyCountObjects
If you want the Apple Event Manager to help your application resolve object specifier records of key form formTest (and if your application doesn’t specify kAEIDoWhose as described on page 6-48), you should provide an object-counting function and an object-comparison function. An object-counting function counts the number of Apple event objects of a specified class in a specified container.
FUNCTION MyCountObjects (desiredClass: DescType;
containerClass: DescType;
theContainer: AEDesc;
VAR result: LongInt): OSErr;
desiredClass
The object class of the Apple event objects to be counted.
containerClass
The object class of the container for the Apple event objects to be counted.
theContainer
A token that identifies the container for the Apple event objects to be counted.
result Your object-counting function should return in this parameter the number of Apple objects of the specified class in the specified container.
DESCRIPTION
The Apple Event Manager calls your object-counting function when, in the course of resolving an object specifier record, the manager requires a count of the number of Apple event objects of a given class in a given container.
SPECIAL CONSIDERATIONS
If the Apple Event Manager receives the result code errAEEventNotHandled after calling an object-counting function, it attempts to use other methods of counting the specified objects, such as calling an equivalent system object-counting function. Thus, an object-counting function that can’t count the specified objects should return errAEEventNotHandled. This allows the Apple Event Manager to try other object-counting functions that may be available.
RESULT CODESnoErr 0 No error occurred
errAEEventNotHandled –1708 The object-counting function is unable to count the specified Apple event objects
SEE ALSO
For more information, see “Writing an Object-Counting Function” on page 6-48.
MyCompareObjects
If you want the Apple Event Manager to help your application resolve object specifier records of key form formTest (and if your application doesn’t specify kAEIDoWhose as described on page 6-48), you should provide an object-counting function and an object-comparison function. After comparing one Apple event object to another or to the data for a descriptor record, an object-comparison function should return TRUE or FALSE in the result parameter.
FUNCTION MyCompareObjects (comparisonOperator: DescType;
object: AEDesc;
objectOrDescToCompare: AEDesc;
VAR result: Boolean): OSErr;
comparisonOperator
The comparison operator. See the description of CreateCompDescriptor on page 6-89 for standard comparison operators at the time of publication of this book. The current version of the Apple Event Registry: Standard Suites lists all the constants for comparison operators.
object A token.
objectOrDescToCompare
A token or some other descriptor record that specifies either an Apple event object or a value to compare to the Apple event object specified by the object parameter.
result Your object-comparison function should return, in this parameter, a Boolean value that indicates whether the values of the object and objectOrDescToCompare parameters have the relationship specified by the comparisonOperator parameter (TRUE) or not (FALSE).
DESCRIPTION
The Apple Event Manager calls your object-comparison function when, in the course of resolving an object specifier record, the manager needs to compare an Apple event object with another or with a value.
It is up to your application to interpret the comparison operators it receives. The meaning of comparison operators differs according to the Apple event objects being compared, and not all comparison operators apply to all object classes.
SPECIAL CONSIDERATIONS
If the Apple Event Manager receives the result code errAEEventNotHandled after calling an object-comparison function, it attempts to use other methods of comparison, such as calling an equivalent system object-comparison function. Thus, an object-comparison function that can’t perform a requested comparison should return errAEEventNotHandled. This allows the Apple Event Manager to try other object-comparison functions that may be available.
RESULT CODESnoErr 0 No error occurred
errAEEventNotHandled –1708 The object-comparison function is unable to compare the specified Apple event objects
SEE ALSO
For more information, see “Writing an Object-Comparison Function” on page 6-50.
MyDisposeToken
If your application requires more than a call to the AEDisposeDesc function to dispose of a token, or if it supports marking callback functions, you must provide one token disposal function. A token disposal function disposes of a specified token.
FUNCTION MyDisposeToken (VAR unneededToken: AEDesc): OSErr;
unneededToken
The token to dispose of.
DESCRIPTION
The Apple Event Manager calls your token disposal function whenever it needs to dispose of a token. It also calls your disposal function when your application calls the AEDisposeToken function. If your application does not provide a token disposal function, the Apple Event Manager calls AEDisposeDesc instead.
Your token disposal function must be able to dispose of all of the token types used by your application.
If your application supports marking, a call to MyDisposeToken to dispose of a mark token lets your application know that it can unmark the objects marked with that mark token.
SPECIAL CONSIDERATIONS
If the Apple Event Manager receives the result code errAEEventNotHandled after calling a token disposal function, it attempts to dispose of the token by some other method, such as calling an equivalent system token disposal function if one is available or, if that fails, by calling AEDisposeDesc. Thus, a token disposal function that can’t dispose of a token should return errAEEventNotHandled. This allows the Apple Event Manager to try other token disposal functions that may be available.
RESULT CODESnoErr 0 No error occurred
errAEEventNotHandled –1708 The token disposal function is unable to dispose of the token
MyGetErrorDesc
If you want to find out which descriptor record is responsible for an error that occurs during a call to the AEResolve function, you can provide an error callback function. An error callback function returns a pointer to an address. The Apple Event Manager uses this address to store the descriptor record it is currently working with if an error occurs during a call to AEResolve.
FUNCTION MyGetErrorDesc (VAR errDescPtr: DescPtr): OSErr;
errDescPtr
A pointer to an address.
DESCRIPTION
Your error callback function simply returns an address. Shortly after your application calls AEResolve, the Apple Event Manager calls your error callback function and writes a null descriptor record to the address returned, overwriting whatever was there previously. If an error occurs during the resolution of the object specifier record, the Apple Event Manager calls your error callback function again and writes the descriptor record—often an object specifier record—to the address returned. If AEResolve returns an error during the resolution of an object specifier record, this address contains the descriptor record responsible for the error.
Normally you should maintain a single global variable of type AEDesc whose address your error callback function returns no matter how many times it is called. Be careful if you use any other method. When recovering from an error, the Apple Event Manager never writes to the address you provide unless it already contains a null descriptor record. Thus, if you don’t maintain a single global variable as just described, you should write null descriptor records to any addresses passed by your error callback function that are different from the addresses returned the first time your function is called after a given call to AEResolve.
If the result code returned by the MyGetErrorDesc function has a nonzero value, the Apple Event Manager continues to resolve the object specifier record as if it had never called the error callback function.
RESULT CODEnoErr 0 No error occurred
MyGetMarkToken
If your application supports marking, you must provide one mark token function. A mark token function returns a mark token.
FUNCTION MyGetMarkToken (containerToken: AEDesc;
containerClass: DescType;
VAR result: AEDesc): OSErr;
containerToken
The Apple event object that contains the elements to be marked with the mark token.
containerClass
The object class of the container that contains the objects to be marked.
result Your mark token function should return a mark token in this parameter.
DESCRIPTION
To get a mark token, the Apple Event Manager calls your mark token function. Like other tokens, the mark token returned can be a descriptor record of any type; however, unlike other tokens, a mark token identifies the way your application will mark Apple event objects during the current session while resolving a single object specifier record that specifies the key form formTest.
A mark token is valid until the Apple Event Manager either disposes of it (by calling AEDisposeToken) or returns it as the result of the AEResolve function. If the final result of a call to AEResolve is a mark token, the Apple event objects currently marked for that mark token are those specified by the object specifier record passed to AEResolve, and your application can proceed to do whatever the Apple event has requested. Note that your application is responsible for disposing of a final mark token with a call to AEDisposeToken, just as for any other final token.
If your application supports marking, it should also provide a token disposal function modeled after the token disposal function described on page 6-99. When the Apple Event Manager calls AEDisposeToken to dispose of a mark token that is not the final result of a call to AEResolve, the subsequent call to your token disposal function lets you know that you can unmark the Apple event objects marked with that mark token. A call to AEDisposeDesc to dispose of a mark token (which would occur if you did not provide a token disposal function) would go unnoticed.
RESULT CODESnoErr 0 No error occurred
errAEEventNotHandled –1708 The mark token function is unable to return a mark token; if the Apple Event Manager gets this result, it attempts to get a mark token by calling the equivalent system marking callback function
SEE ALSO
For more information, see “Writing Marking Callback Functions,” which begins on page 6-53.
MyMark
If your application supports marking, you must provide one object-marking function. An object-marking function marks a specific Apple event object.
FUNCTION MyMark (theToken: AEDesc; markToken: AEDesc;
markCount: LongInt): OSErr;
theToken The token for the Apple event object to be marked.
markToken The mark token used to mark the Apple event object.
markCount The number of times MyMark has been called for the current mark token (that is, the number of Apple event objects that have so far passed the test, including the element to be marked).
DESCRIPTION
To mark an Apple event object using the current mark token, the Apple Event Manager calls the object-marking function provided by your application. In addition to marking the specified object, your MyMark function should record the mark count for each object that it marks. The mark count recorded for each marked object allows your application to determine which of a set of marked tokens pass a test, as described in the next section for the MyAdjustMarks function.
RESULT CODESnoErr 0 No error occurred
errAEEventNotHandled –1708 The MyMark function is unable to mark the specified Apple event object; if the Apple Event Manager gets this result, it attempts to mark the object by calling the equivalent system object-marking function
SEE ALSO
For more information, see “Writing Marking Callback Functions,” which begins on page 6-53.
MyAdjustMarks
If your application supports marking, you must provide one mark-adjusting function. A mark-adjusting function adjusts the marks made with the current mark token.
FUNCTION MyAdjustMarks (newStart, newStop: LongInt;
markToken: AEDesc): OSErr;
newStart The mark count value (provided when the MyMark callback routine was called to mark the object) for the first object in the new set of marked objects.
newStop The mark count value (provided when the MyMark callback routine was called to mark the object) for the last object in the new set of marked objects.
markToken The mark token for the marked objects.
DESCRIPTION
When the Apple Event Manager needs to identify either a range of elements or the absolute position of an element in a group of Apple event objects that pass a test, it can use your application’s mark-adjusting function to unmark objects previously marked by a call to your marking function. For example, suppose an object specifier record specifies “any row in the table ‘MyCustomers’ for which the City column is ‘San Francisco.’” The Apple Event Manager first uses the appropriate object accessor function to locate all the rows in the table for which the City column is “San Francisco” and calls the application’s marking function repeatedly to mark them. It then generates a random number between 1 and the number of rows it found that passed the test and calls the application’s mark-adjusting function to unmark all the rows whose mark count does not match the randomly generated number. If the randomly chosen row has a mark count value of 5, the Apple Event Manager passes the value 5 to the mark-adjusting function in both the newStart parameter and the newStop parameter, and passes the current mark token in the markToken parameter.
When the Apple Event Manager calls your MyAdjustMarks function, your application must dispose of any data structures that it created to mark the previously marked objects.
RESULT CODESnoErr 0 No error occurred
errAEEventNotHandled –1708 The MyAdjustMarks function is unable to adjust the marks as requested; if the Apple Event Manager gets this result, it attempts to adjust the marks by calling the equivalent system mark-adjusting function
SEE ALSO
For more information, see “Writing Marking Callback Functions” on page 6-53.
Summary of Resolving and Creating Object Specifier Records
Pascal Summary
Constants
CONST
gestaltAppleEventsAttr = 'evnt'; {selector for Apple events}
gestaltAppleEventsPresent = 0; {if this bit is set, Apple }
{ Event Manager is available}
{logical operators for descriptor records with keyword }
{ keyAELogicalOperator}
kAEAND = 'AND ';
kAEOR = 'OR ';
kAENOT = 'NOT ';
{absolute ordinals used as key data in an object specifier }
{ record with key form formAbsolutePosition}
kAEFirst = 'firs';
kAELast = 'last';
kAEMiddle = 'midd';
kAEAny = 'any ';
kAEAll = 'all ';
{relative ordinals used as key data in an object specifier record }
{ with key form formRelativePosition}
kAENext = 'next';
kAEPrevious = 'prev';
{keywords for object specifier records}
keyAEDesiredClass = 'want'; {object class ID}
keyAEContainer = 'from'; {description of container}
keyAEKeyForm = 'form'; {key form}
keyAEKeyData = 'seld'; {key data for specified key form}
{keywords for range descriptor records}
keyAERangeStart = 'star'; {beginning of range}
keyAERangeStop = 'stop'; {end of range}
{values for the keyAEKeyForm field of an object specifier record}
formAbsolutePosition = 'indx' ; {for example, 1 = first }
{ element in container, -2 = }
{ second from end of container}
formRelativePosition = 'rele'; {key data specifies element }
{ before or after container}
formTest = 'test'; {key data specifies a test}
formRange = 'rang'; {key data specifies a range}
formPropertyID = 'prop'; {key data is property ID}
formName = 'name'; {key data is element's name}
{descriptor types used to identify Apple event objects}
typeObjectSpecifier = 'obj '; {object specifier record, often }
{ used as keyAEContainer}
typeObjectBeingExamined = 'exmn'; {used as keyAEContainer}
typeCurrentContainer = 'ccnt'; {used as keyAEContainer}
noPortErr –903 Client hasn’t set 'SIZE' resource to indicate awareness of high-level events
destPortErr –906 Server hasn’t set 'SIZE' resource to indicate awareness of high-level events, or else is not present
sessClosedErr –917 The kAEDontReconnect flag in the sendMode parameter was set, and the server quit and then restarted
errAECoercionFail –1700 Data could not be coerced to the requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAECorruptData –1702 Data in an Apple event could not be read
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
errAENewerVersion –1706 Need a newer version of the Apple Event Manager
errAENotAppleEvent –1707 Event is not an Apple event
errAEEventNotHandled –1708 Event wasn’t handled by an Apple event handler
errAEReplyNotValid –1709 AEResetTimer was passed an invalid reply
errAEUnknownSendMode –1710 Invalid sending mode was passed
errAEWaitCanceled –1711 User canceled out of wait loop for reply or receipt
errAETimeout –1712 Apple event timed out
errAENoUserInteraction –1713 No user interaction allowed
errAENotASpecialFunction –1714 The keyword is not valid for a special function
errAEParamMissed –1715 Handler cannot understand a parameter the client considers required
errAEUnknownAddressType –1716 Unknown Apple event address type
errAEHandlerNotFound –1717 No handler found for an Apple event or a coercion, or no object callback function found
errAEReplyNotArrived –1718 Reply has not yet arrived
errAEIllegalIndex –1719 Not a valid list index
errAEImpossibleRange –1720 The range is not valid because it is impossible for a range to include the first and last objects that were specified; an example is a range in which the offset of the first object is greater than the offset of the last object
errAEWrongNumberArgs –1721 The number of operands provided for the kAENOT logical operator is not 1
errAEAccessorNotFound –1723 There is no object accessor function for the specified object class and token descriptor type
errAENoSuchLogical –1725 The logical operator in a logical descriptor record is not kAEAND, kAEOR, or kAENOT
errAEBadTestKey –1726 The descriptor record in a test key is neither a comparison descriptor record nor a logical descriptor record
errAENotAnObjectSpec –1727 The objSpecifier parameter of AEResolve is not an object specifier record
errAENoSuchObject –1728 A run-time resolution error, for example: object specifier record asked for the third element, but there are only 2.
errAENegativeCount –1729 Object-counting function returned negative value
errAEEmptyListContainer –1730 The container for an Apple event object is specified by an empty list
errAEUnknownObjectType –1731 Descriptor type of token returned by AEResolve is not known to server application
errAERecordingIsAlreadyOn –1732 Attempt to turn recording on when it is already on
Listing 7-0
Table 7-0
Introduction to Scripting
Contents
About Scripts and Scripting Components7-4
Script Editors and Script Files7-6
Scripting Components and Scriptable Applications7-8
Scripting Components and Applications That Execute Scripts7-11
Making Your Application Scriptable7-14
About Apple Event Terminology Resources7-15
How AppleScript Uses Terminology Information7-17
Dynamic Loading of Terminology Information7-20
Making Your Application Recordable7-20
Manipulating and Executing Scripts7-22
Compiling, Saving, Modifying, and Executing Scripts7-24
Using a Script Context to Handle an Apple Event7-25
Introduction to Scripting
This chapter provides an overview of the tasks involved in making your application scriptable and recordable. This chapter also introduces some of the ways your application can use the Component Manager and scripting components to manipulate and execute scripts. The three chapters that follow provide detailed information, including sample code, about the topics introduced in this chapter.
The chapter “Introduction to Interapplication Communication” in this book describes the Open Scripting Architecture (OSA) and its relationship to the Apple Event Manager and other parts of the IAC architecture. If your application supports the appropriate core and functional-area events defined in the Apple Event Registry: Standard Suites, you can make it scriptable (that is, capable of responding to Apple events sent by scripting components) by providing an Apple event terminology extension ('aete') resource. This chapter describes some of the tasks involved in making your application scriptable and introduces the 'aete' resource. The next chapter, “Apple Event Terminology Resources,” describes in detail how to create an 'aete' resource.
This chapter also introduces Apple event recording and the use of the standard scripting component routines to manipulate and execute scripts. The chapter “Recording Apple Events” describes in detail how to make your application recordable, and the chapter “Scripting Components” describes how to use the standard scripting component routines.
To use this chapter or any of the chapters that follow, you should be familiar with the chapters “Introduction to Apple Events” and “Responding to Apple Events” in this book. If you plan to make your application recordable, you should also read the chapters “Creating and Sending Apple Events” and “Resolving and Creating Object Specifier Records.”
The AppleScript Software Developers’ Kit (available from APDA) provides development tools, sample applications, and information about the AppleScript language that you will find useful when you begin to apply the information in this chapter to your application.
If you are developing a scripting component, you should provide support for the standard scripting component routines described in the chapter “Scripting Components,” and you should read the instructions for creating components in the chapter “Component Manager” in Inside Macintosh: More Macintosh Toolbox.
This chapter begins with an overview of scripts and scripting components. The rest of the chapter describes how the OSA makes it possible to
n make your application scriptable
n make your application recordable
n have your application manipulate and execute scripts
About Scripts and Scripting Components
A script is any collection of data that, when executed by the appropriate program, causes a corresponding action or series of actions. The Open Scripting Architecture (OSA) provides a standard mechanism that allows users to control multiple applications with scripts written in a variety of scripting languages. Each scripting language has a corresponding scripting component. Each scripting component supports the standard scripting component routines described in the chapter “Scripting Components” in this book.
When a scripting component executes a script, it performs the actions described in the script, including sending Apple events to applications if necessary. Like other components that use the Component Manager, scripting components can provide their own routines in addition to the standard routines that must be supported by all components of the same type.
Scripting components typically implement a text-based scripting language based on Apple events. For example, the AppleScript component implements AppleScript, the standard user scripting language defined by Apple Computer, Inc. This book uses AppleScript examples to demonstrate how applications can interact with scripting components.
Other scripting components may support the standard scripting component routines in different ways. Scripting components need not implement a text-based scripting language, or even one that is based on Apple events. For example, specialized scripting components can play sounds, execute XCMDs, or perform almost any other action when they execute scripts.
This chapter describes three ways that you can take advantage of the OSA:
n You can make your application scriptable, or capable of responding to Apple events sent to it by a scripting component. An application is scriptable if it
n Responds to the appropriate standard Apple events as described in the chapter “Responding to Apple Events” in this book.
n Provides an Apple event terminology extension ('aete') resource describing the Apple events that your application supports and the user terminology that corresponds to those events. The 'aete' resource allows scripting components to interpret scripts correctly and send the appropriate Apple events to your application during script execution.
n You can make your application recordable—that is, capable of sending Apple events to itself to report user actions to the Apple Event Manager for recording purposes. After a user has turned on recording for a particular scripting component, the scripting component receives a copy of every subsequent Apple event that any application on the local computer sends to itself. The scripting component records such events in the form of a script.
n You can have your application manipulate and execute scripts with the aid of a scripting component. To do so, your application must
n Use the Component Manager to open a connection with the appropriate component.
n Use the standard scripting component routines described in the chapter “Scripting Components” to record, edit, compile, save, load, or execute scripts.
Users of scriptable applications can execute scripts to perform tasks that might otherwise be difficult to accomplish, especially repetitive or conditional tasks that involve multiple applications. For example, a user can execute an AppleScript script to locate database records with specific characteristics, create a series of graphs based on those records, import the graphs into a page-layout document, and send the document to a remote computer on the network via electronic mail. When a user executes such a script, the AppleScript component attempts to perform the actions the script describes, including sending Apple events when necessary.
To respond appropriately to the Apple events sent to it by the AppleScript component, the database application in this example must be able to locate records with specific characteristics so that it can identify and return the requested data. These characteristics are described by an object specifier record that is part of an Apple event supported by the application. Also, the other applications involved must support Apple events that manipulate the data in the ways described in the script. Each application in this example must also provide an 'aete' resource describing the Apple events that the application supports and the user terminology that corresponds to those events, so that the AppleScript component can interpret the script correctly.
Even with little or no knowledge of a particular scripting language, users of applications that are recordable as well as scriptable can record simple scripts. More knowledgeable users may also wish to record their actions as scripts with recordable applications and then edit or combine scripts as needed.
An application that uses scripting components to manipulate and execute scripts need not be scriptable; however, if it is scriptable, it can execute scripts that control its own behavior. In other words, it can perform tasks by means of scripts and allow users to modify those scripts to suit their own needs.
The next three sections provide an overview of the way scripting components can interact with applications.
Script Editors and Script Files
A script editor is an application that allows users to record, edit, save, and execute scripts. For example, the AppleScript component uses the services of the Script Editor application.
Figure 7-1 shows an AppleScript script displayed in a Script Editor window. The Record, Stop, and Run buttons control a script in much the same way that the equivalent buttons on a cassette recorder control an audio tape. A script comment at the top of the window describes what the script does. Users with some knowledge of a text-based scripting language such as AppleScript can use Script Editor to modify recorded scripts or write their own scripts.
Figure 7-1 A script window in the Script Editor application
Script Editor provides entry-level scripting capabilities, but it is not intended for intensive script development. Users who wish to write complex scripts may replace Script Editor with more sophisticated editors that provide specialized debugging and development tools.
A script like the one in Figure 7-1 can be stored in a script file represented by an icon in the Finder, or it can be stored within an application or one of its documents. Figure 7-2 shows the four icons representing the files in which Script Editor stores scripts.
Figure 7-2 Script file icons in the Finder and corresponding user actions
Script Editor and similar script-editing applications allow users to store scripts using three file types:
n A compiled script file has the file type 'osas' and contains the script data as a resource of type 'scpt'. Before executing the script in a compiled script file, a user must first open the script from the Finder or from an application such as Script Editor. After opening a compiled script in an application that supports script editing, the user can view the script, modify it if necessary, and execute it.
n A script application has the file type 'APPL' and contains the script data as a resource of type 'scpt'. Its kind is “application.” A script application takes one of two forms, each with its own icon:
n A script application with the creator signature 'aplt'. A user double-clicks the icon to trigger the script.
n A script application with the creator signature 'dplt'. A user can drag the icon for another file or a folder over this script application’s icon to trigger a script that acts on that object.
By default, when a user triggers the script in either kind of script application, a splash screen appears that allows the user either to quit or to run the script. Users can also save a script application in a form that bypasses the splash screen, running the script immediately after the user double-clicks its icon.
n A script text file contains only a plain-text version of uncompiled scripting-language statements. This format is useful primarily as a last resort for saving a script that can’t be compiled because of syntax errors or other problems. It is also useful for exchanging unstyled text with other text-based applications. A user must open a script text file in a script editor and successfully compile it before it will execute.
Like sound resources, scripts can be stored within applications and documents as well as in distinct files that can be manipulated from the Finder. Your application can use the standard scripting component routines to manipulate and execute both its own internally stored scripts and scripts stored as separate files whose icons appear in the Finder. For more information about script storage formats, see “Saving Script Data” on page 10-12.
The next two sections describe how scripting components interact with scriptable applications and with applications that execute scripts.
Scripting Components and Scriptable Applications
Scripting components control the behavior of scriptable applications by means of Apple events. For example, when the AppleScript component executes the AppleScript script shown in Figure 7-1, it sends the Apple events shown in Figure 7-3 to trigger the actions described by the script. The client application in this example would most commonly be a script editor but could also be any other application that uses standard scripting component routines to manipulate and execute scripts.
Figure 7-3 How the AppleScript component executes a script
As described in the chapter “Introduction to Apple Events” in this book, a client application is any application that uses Apple events to request a service or information. A client application that executes a script does not send the corresponding Apple events itself; instead, it uses scripting component routines to manipulate and execute the script. The scripting component sends Apple events when necessary to trigger the actions described in the script. Similarly, a scriptable application that responds to the Apple events sent by a scripting component can be considered the server application for those Apple events.
When a scripting component evaluates a script, it attempts to perform all the actions described in the script, including sending Apple events when necessary. In the example shown in Figure 7-3, the AppleScript component first performs the action described in the first tell statement:
tell application "SurfWriter"
copy table "Summary of Sales" of document¬
"Sales Report" to Totals
end tell
To perform this action, the AppleScript component sends a Get Data event to the SurfWriter application requesting the data from the specified table. The SurfWriter application returns the data to the AppleScript component in a standard reply Apple event, and the AppleScript component sets the value of the variable Totals to the data returned by SurfWriter.
Then the AppleScript component performs the action described in the second tell statement:
tell application "SurfCharter"
copy Totals to Chart 1 of document "Sales Chart"
end tell
In this case, the AppleScript component sends a Set Data event to the SurfCharter application that sets the specified chart to the value of the variable Totals.
Both SurfWriter and SurfCharter are server applications for the Apple events sent by the AppleScript component, because they are performing services in response to requests made by the client application via the script.
To send the appropriate Apple events to a scriptable application while executing a script, a scripting component must obtain information about the nature of that application’s support for Apple events and the human-language terminology to associate with those events. A scriptable application provides this information in the form of an Apple event terminology extension ('aete') resource. A scripting component uses both the 'aete' resource provided by a scriptable application and the Apple event user terminology ('aeut') resource provided by the scripting component itself to obtain the information it needs to execute a script that controls that application.
See “Making Your Application Scriptable,” which begins on page 7-14, for an overview of the tasks you should perform to make your application scriptable and a more detailed description of the 'aete' and 'aeut' resources. See “Making Your Application Recordable” on page 7-20 for an overview of the tasks you should perform if you want your application to be recordable as well as scriptable.
Scripting Components and Applications That Execute Scripts
To store and execute scripts as a client application, your application must first establish a connection with a scripting component registered with the Component Manager on the same computer. Each scripting component can manipulate and execute scripts written in the corresponding scripting language when your application calls the standard scripting component routines.
Your application can use scripting component routines to
n obtain a handle to a script in a form that can be saved, and load the script again when necessary
n allow users to modify scripts that have been previously saved
n compile and execute scripts
n redirect Apple events to script contexts
n supply application-defined functions for use by scripting components
n control the recording process directly, turning recording off and on and saving the recorded script for use by your application
Your application can perform these tasks as a client application regardless of whether it is scriptable or recordable. If your application is scriptable, however, it can execute scripts that control its own behavior, thus acting as both the client application and the server application for the corresponding Apple events. For example, your application can allow users to associate a script with a custom menu command that performs a series of routine actions on a selected object, sets preferences, or automates other actions within your application.
You can also use scripting component routines to execute scripts that perform tasks for your application with the aid of other applications. For example, a user of a word-processing application might be able to attach a script to a specific word so that the application executes the script whenever that word is double-clicked. Such a script could trigger Apple events that cause other applications to look up and display related information, run a QuickTime movie, perform a calculation, play a voice annotation, and so on.
Your application can associate a script with either Apple event objects or application-defined objects. Almost any user action can be used to trigger such a script: choosing a menu command, clicking a button, tabbing from one table cell to another, and so on. The script can be executed directly by the application when it detects a triggering action; or, if the script is associated with an Apple event object in the form of a script context, it can be executed automatically when a specified Apple event performs an action on that object.
The rest of this section describes one way that an application could execute such a script. Suppose a forms application allows users to create custom forms that can include scripts associated with specific fields on the form. These scripts are executed when the user presses Enter or Tab in the appropriate field. For the purposes of this example, it doesn’t matter whether a field with which a script is associated is an Apple event object (which can be described in an object specifier record) or some other application-defined object (which can’t be described in an object specifier record).
A company could use the forms application to create a custom order form for taking telephone orders. If the customer has ordered from the company before, the user can quickly retrieve the customer’s address from the company database by typing the customer’s name in a field and pressing the Tab key. In response, the application executes the script associated with the field. The script might look like this in AppleScript:
set custName to field "Customer Name"
tell application SurfDB
copy the first record in the table MyAddresses ¬
whose cell "Customer Name" = custName to Address
end tell
set field "Street" to item 2 of Address
set field "City" to item 3 of Address
set field "Zip" to item 4 of Address
To execute such a script (or to manipulate it any other way, such as when the form is first created), the forms application must previously have established a connection with the appropriate scripting component—in this case, the AppleScript component. When the user enters a customer name and presses Tab, the forms application calls scripting component routines to execute the script. As shown in Figure 7-4, the AppleScript component first sends the forms application a Get Data event that requests the contents of the “Customer Name” field and sets the variable custName to that value. It then sends SurfDB a Get Data event that requests the appropriate address information and copies it to the variable Address. (The replies to the Get Data events are not shown in Figure 7-4.) Finally, the AppleScript component sends the forms application a Set Data event that copies the address information from the variable Address to the appropriate fields.
The AppleScript component needs to maintain the binding of the variables custName and Address throughout execution of the script. Scripting components bind variables with the aid of a script context, which is a script that maintains context information for the execution of other scripts. An application specifies a script context when it executes a script. The forms application in Figure 7-4 provides a context for the scripting component to use whenever it executes a script associated with a button.
Figure 7-4 How an application uses the AppleScript component to execute a script
In the example shown in Figure 7-4, the application executes the script directly when the cursor is in the appropriate field and the user presses Tab or Enter. Your application can also associate such a script with an object in the form of a script context, so that the script context is executed whenever a specified Apple event acts on the field. The section “Using a Script Context to Handle an Apple Event,” which begins on page 7-25, describes this approach in more detail.
See “Manipulating and Executing Scripts,” which begins on page 7-22, for an overview of methods your application can use to save and load script data, compile source data, and perform other useful tasks with scripting component routines. The chapter “Scripting Components” in this book provides full implementation details, including sample code and human interface guidelines for associating scripts with objects.
Making Your Application Scriptable
To make your application scriptable, you need to
n define a hierarchy of Apple event objects within your application that you want client applications to be able to identify—that is, which objects can be contained by other Apple event objects in your application, which properties each kind of object can have, and so on
n write Apple event handlers, object accessor functions, and other routines required to implement the Apple events and related object classes that you want to support
n create an 'aete' resource
The chapters “Introduction to Apple Events,” “Responding to Apple Events,” and “Resolving and Creating Object Specifier Records” in this book describe how to perform the first two tasks. The extent to which scripts can control your application depends mainly on the extent of your application’s support for Apple events. For example, if your application does not provide the Apple event handlers and object accessor functions required to locate and manipulate windows, users will not be able to use scripts to control your application’s windows. Although you should use the definitions in the Apple Event Registry: Standard Suites whenever possible, you have considerable freedom to extend or limit your implementation of the standard Apple events according to the needs of your application.
The OSA makes it possible to design new kinds of applications that always operate in the background and can be controlled only by means of scripts. For example, it is possible to design a simple telecommunications program that can log on to a network, send and receive text files created by another application, and perform other basic operations in response to scripts without providing any other form of user interface. Such an application would not need to support Apple events that control window movement, the File menu, or the Edit menu; instead, it would need to support only those Apple events that execute its basic telecommunications operations.
At the other extreme, some applications allow users to arrange windows, palettes, and dialog boxes on their screen in many different ways, or to customize menus or other aspects of the presentation of information. If such an application can respond to scripts that control windows, dialog boxes, specialized preferences, and other aspects of the presentation of information, it can allow users who might not otherwise explore those capabilities to take advantage of them. For example, a naive user could execute a script that sets up a powerful word processor with the appropriate menus, window and palette arrangement, and formatting templates for a particular task, such as producing a company newsletter.
Scripting components use 'aeut' and 'aete' resources to associate Apple event codes supported by your application with corresponding human-language terms used in scripts that control your application. Each scripting component supplies an 'aeut' resource, and each scriptable application provides an 'aete' resource. The next section introduces the 'aeut' and 'aete' resources.
About Apple Event Terminology Resources
As explained in the chapter “Introduction to Apple Events” in this book, applications can support different combinations of the standard suites of Apple events. Applications can also extend the definitions of individual Apple events and object classes, or define custom Apple events and object classes. Scripting components use the Apple event user terminology resources, 'aeut' and 'aete', to associate the IDs, keywords, and other codes used in Apple events with the corresponding human-language terms used in scripts that control your application.
The Apple event user terminology ('aeut') resource contains terminology information for all the standard suites of Apple events defined in the Apple Event Registry: Standard Suites. The resource consists of a sequence of concatenated arrays that map human-language names to each of the following:
n the ID defined for each suite
n the Apple events defined for each suite
n the parameters defined for each Apple event
n the Apple event object classes defined for each suite
n the properties defined for each object class
n the elements defined for each object class
n the key forms defined for each element class
n the comparison operators defined for each suite
n the values for enumerators defined for each suite
Each scripting component provides its own 'aeut' resource. A scripting component can also provide different versions of the 'aeut' resource; for example, the user terminology provided by the 'aeut' resource for the AppleScript Japanese dialect component is in Japanese. The IDs, keywords, and other codes listed in the 'aeut' resource are based on the Apple Event Registry: Standard Suites and do not vary from one version to another.
An 'aete' resource has the same format as the 'aeut' resource but serves a different purpose. Each scriptable application must include its own 'aete' resource describing which of the standard suites listed in the 'aeut' resource it supports and providing other application-specific information. Since the human-language equivalents for the standard suites are defined in the 'aeut' resource, applications that support standard suites without any modifications do not have to define such equivalents; instead, they can simply list, in the 'aete' resource, the suites they support. The scripting component associates the standard suites listed in the 'aete' resource with the corresponding Apple event descriptions in its 'aeut' resource.
Applications can also use the 'aete' resource to describe extensions to the standard suites, such as additional parameters for standard Apple events, additional properties and element classes for the standard Apple event object classes, and additional key forms for each element class. Information about such extensions must be included in the appropriate arrays of the 'aete' resource, along with the equivalent human-language terms. Similarly, an application can use the 'aete' resource to describe the parts of each standard suite it supports (if it doesn’t support the entire suite) and any custom Apple events or Apple event object classes defined by the application.
The human language in which your Apple event extensions or custom Apple events are displayed in scripts depends on the corresponding user terminology you specify in your application’s 'aete' resource. Therefore, if your application implements such extensions or custom Apple events, you must provide a separate version of this resource for each localized version of your application.
Scripting components can use the information in the 'aete' and 'aeut' resources in a variety of ways. The next section, “How AppleScript Uses Terminology Information,” describes how the AppleScript component uses these resources when it executes or records a script. The next chapter, “Apple Event Terminology Resources,” describes how to create an 'aete' resource for your application.
If you want users to be able to control your application with scripts written in the AppleScript scripting language, you also need to know how the AppleScript component interprets AppleScript commands that trigger Apple events. In this way, you can make sure you support Apple events and specify the user terminology for your 'aete' resource in a way that translates easily into AppleScript statements. The section “Defining Terminology for Use by the AppleScript Component,” which begins on page 8-3, discusses these issues. If you implement Apple events so that they translate into logical and useful AppleScript scripts, your implementation will probably work well with other scripting components that resemble AppleScript.
How AppleScript Uses Terminology Information
The manner in which the AppleScript component uses the information in 'aete' resources depends on specific characteristics of the AppleScript scripting language. An AppleScript expression consists of an internal compiled form and corresponding expressions in dialects, or versions of the AppleScript scripting language that resemble different human languages. Users can select the dialect they want to use from within the Script Editor application. If a script is displayed in a window and the user selects a different dialect, the AppleScript component converts the script to the new dialect. Users can install additional dialects as necessary.
This section describes how the AppleScript component uses the information in the 'aeut' and 'aete' resources, not how it obtains that information. For a description of the methods available to scripting components for loading information from terminology resources, see “Dynamic Loading of Terminology Information” on page 7-20.
Figure 7-5 shows how the AppleScript component uses information from its 'aeut' resource and an application’s 'aete' resource to execute a script that consists of AppleScript statements displayed in a script editor window. When a user executes the script from the script editor (for example, by pressing the Run button in the Script Editor application), the AppleScript component first compiles the script into the equivalent compiled expressions, using information from its 'aeut' resource and the application’s 'aete' resource to map application-specific terms in the script with the equivalent Apple events and Apple event parameters. The AppleScript component then evaluates each expression and performs actions or sends Apple events as appropriate.
For example, the AppleScript component evaluates the expression
2*3
as the value 6. The AppleScript component can then decompile and display this value in the script editor window, assign it to a variable, or otherwise manipulate it according to the rest of the script. However, to compile the statement
print Chart 1 of document "Sales Report"
the AppleScript component uses its 'aeut' resource and the SurfWriter application’s 'aete' resource to associate the terms used in the script with the Print Apple event, the object class for charts, and the object class for documents, so that it can describe the event accurately in the form of a compiled expression. When the AppleScript component evaluates the compiled expression, it creates and sends a Print event whose direct parameter is an object specifier record that the SurfWriter application can resolve as the specified chart. The SurfWriter application then handles the Apple event by printing the chart as requested.
Figure 7-5 Role of the 'aete' and 'aeut' resources when the AppleScript component compiles and executes a script
Note that although Figure 7-5 shows only one Apple event generated as a result of executing a script, the AppleScript component could also send a series of Apple events to several different applications, depending on the content of the script.
A recordable application generally needs to be able to send itself a subset of the Apple events that it can handle as a scriptable application. A recordable event is any Apple event that any recordable application sends to itself while recording is turned on for the local computer (with the exception of events that the application explicitly identifies as not for recording purposes). After a user turns on recording from the Script Editor application, the Apple Event Manager sends copies of all recordable events to Script Editor. A scripting component previously selected by the user handles each copied event for Script Editor by translating the event and recording the translation as part of a Script Editor script. When a scripting component executes a recorded script, it sends the corresponding Apple events to the applications in which they were recorded.
Every scripting component must be able to handle copies of recordable events sent to a recording process (such as Script Editor) by recording them in an appropriate form. For example, as shown in Figure 7-6, the AppleScript component records copies of recordable events in the form of compiled expressions. The AppleScript component can then use information from its 'aeut' resource and the application’s 'aete' resource to translate the compiled expressions into the appropriate human-language terms and display them as AppleScript statements in the script editor window. When the user opens a recorded script in Script Editor and presses Run, the AppleScript component recompiles the script if necessary and sends the Apple events described by the compiled expressions to the SurfWriter application, just as in Figure 7-5.
Figure 7-6 Role of the 'aete' and 'aeut' resources when the AppleScript component records and decompiles a script
If the user copies a chart from one document to another document and the SurfWriter application performs this task by sending itself Apple events, the equivalent statements in the recorded script might look something like this:
tell application "SurfWriter"
select Chart 1 of document "Sales Chart"
copy
select paragraph 3 of document "Monthly Report"
paste
end tell
To display these statements in the script editor window, the AppleScript component first translates the Set Data, Copy, and Paste Apple events sent by the recordable application into compiled expressions. It then uses information from its 'aeut' resource and the application’s 'aete' resource to decompile the compiled expressions and pass the equivalent source data to the script editor for display to the user. After completing a recording session, the user can edit and save the resulting script and execute it again at any time.
As shown in Figure 7-5 and Figure 7-6, the AppleScript component uses information it obtains from the 'aeut' and 'aete' resources when it is compiling and decompiling scripts. Other scripting components might use the same information during execution or recording, or in other ways that are specific to each component.
Dynamic Loading of Terminology Information
When a scripting component needs information about the user terminology defined in your application’s 'aete' resource, it sends a Get AETE event to your application. If your application does not handle the Get AETE event, the scripting component reads the terminology information it needs directly from your application’s 'aete' resource.
Your application does not need to handle the Get AETE event unless it provides separate 'aete' resources for plug-in components. If your application does provide separate plug-in components, the Get AETE event allows it to gather terminology information from the 'aete' resources for the components that are currently running and add that information to the reply event.
If your application handles the Get AETE event, you must also provide a scripting size resource. A scripting size resource is a resource of type 'scsz' that provides information about an application’s capabilities and preferences for use by scripting components.
To take advantage of dynamic loading, your application must be running. Note that if your application does not provide a handler for the Get AETE event, the scripting component can obtain terminology information directly from your application’s 'aete' resource even if your application is not running.
Making Your Application Recordable
If you decide to make your application scriptable, you can also make it recordable. A recordable application is an application that uses Apple events to report user actions to the Apple Event Manager for recording purposes. A recordable event is any Apple event that a recordable application sends to itself while recording is turned on for the local computer (with the exception of events sent with the kAEDontRecord flag set in the sendMode parameter of AESend).
When a user turns on recording by clicking the Record button in the Script Editor application, the Apple Event Manager sends copies of all subsequent recordable events to Script Editor. The AppleScript component handles each copied event for Script Editor by translating it into compiled expressions and recording the compiled expressions as part of a script. (Figure 7-6 on page 7-19 shows how the AppleScript component uses the 'aete' and 'aeut' resources when it records a script.) The user can view the equivalent decompiled source data in Script Editor while the script is being recorded. When a user executes a recorded script, the AppleScript component sends the corresponding Apple events to the applications in which they were recorded.
Applications generally have two parts: the code that implements the application’s user interface and the code that actually performs the work of the application when the user manipulates the interface. One way to make your application recordable is to separate these two parts of your application, using Apple events to connect user actions with the work your application performs. This is called factoring your application. In a fully factored application, almost all tasks are carried out in response to Apple events. The application translates low-level events that result in significant actions into recordable Apple events and then sends them to itself.
Factoring your application is the recommended method of making your application recordable. However, it is also possible for your application to report user actions by means of Apple events even though it actually performs those actions by some means other than Apple events. You can indicate that you want the Apple Event Manager to record events in this manner, without executing them, by adding the constant kAEDontExecute to the sendMode parameter of AESend.
Before you decide how to map the user’s potential actions to recordable Apple events supported by your application, you need to answer these questions:
n What are the significant (that is, undoable) actions a user can perform with your application that you want to record?
n Which actions can you execute by means of Apple events, and which actions should cause Apple events to be sent but not executed?
n How do you want to record actions that can be described in a scripting language in several different ways?
For example, if your application is a word processor, the user’s selection of a range of text should probably not generate an Apple event, because users often select various different pieces of text before deciding to do something to the selection. However, if a user changes the font of a selection, a recordable word processor should generate a corresponding Apple event so that the scripting component can record the change.
In general, a recordable application should generate Apple events for any user action that the user could reverse by choosing Undo. A recordable application can usually handle a greater variety of Apple events than it can record, because it must record the same action the same way every time even though Apple events might be able to trigger that action in several different ways.
For more information about recordable applications, factoring, and the Apple Event Manager’s recording mechanism, see the chapter “Recording Apple Events” in this book. For a description of the role of the 'aete' and 'aeut' resources when the AppleScript component records a script, see “How AppleScript Uses Terminology Information,” which begins on page 7-17.
Manipulating and Executing Scripts
Your application can use scripting component routines to manipulate and execute scripts written in any scripting language based on the OSA. This section describes how scripting components use script data and summarizes some of the tasks your application can perform by calling the standard scripting component routines.
Your application can manipulate and execute scripts regardless of whether it is scriptable or recordable. However, if your application is scriptable, you can easily make it capable of manipulating and executing scripts that control its own behavior. For example, the forms application shown in Figure 7-4 on page 7-13 uses standard scripting component routines to execute a script whenever the cursor is in the appropriate field and the user presses Enter or Tab. Applications can also use scripting component routines to allow users to edit, recompile, save, and load such scripts in order to adapt them to their own purposes.
Before using any scripting component routines, your application must open a connection with at least one scripting component. After opening a connection with a component, your application receives a component instance that it can use as the first parameter for any scripting component routine. You can use the Component Manager to establish a connection with the generic scripting component or to establish an explicit connection with any other scripting component. Your application can open connections with different scripting components under different circumstances and, if necessary, simultaneously.
To manipulate or execute scripts written in any scripting language based on the OSA, your application can open a connection with the generic scripting component. The generic scripting component in turn attempts to open connections dynamically with the appropriate scripting component for a given script. If your application opens a connection with the generic scripting component, it can load and execute scripts created by any scripting component that is registered with the Component Manager on the current computer. The generic scripting component also provides routines that allow you to determine which scripting component created a particular script and to perform other useful tasks when you are using multiple scripting components.
To manipulate and execute scripts written in a single scripting language only, your application can open an explicit connection with the scripting component for that language. In this case your application can load and execute only those scripts that were created by that component; however, your application can also take advantage of additional routines and other special capabilities provided by the component.
After your application has established a connection with the appropriate scripting component for an existing script, it can use the standard scripting component routines to execute scripts. A script that has not yet been compiled consists of source data, or statements in a scripting language. Before executing source data, your application must use scripting component routines to compile it so that the scripting component can keep track of it in memory and execute it.
Scripting components can refer to at least three kinds of script data in memory:
n A compiled script consists of compiled code that an application can decompile into source data or execute using the standard scripting component routines.
n A script value consists of an integer, a string, a Boolean value, constants, PICT data, or any other fixed data returned or used by a scripting component in the course of executing a script.
n A script context maintains context information for the execution of other scripts. A script context can also contain executable statements in a scripting language. Like a compiled script, a script context can be decompiled as source data.
For example, a script context can contain user-defined handlers for specific Apple events. In AppleScript, a script context that contains such handlers or other executable statements is called a script object. Handlers in a script object resemble HyperTalk message handlers. They consist of AppleScript statements and have no corresponding entry in Apple event dispatch tables.
Scripting components keep track of script data in memory by means of script IDs of type OSAID.
TYPE OSAID = LongInt;
A scripting component assigns a script ID to a compiled script or script context whenever the component creates or loads the corresponding script data. The scripting component routines that compile, load, and execute scripts all return script IDs, and you must pass valid script IDs to many of the other routines that manipulate scripts.
Applications most commonly use scripting component routines to
n compile source data and execute the resulting compiled script, so that a user can create a new script and execute it immediately from within the application
n get a handle to script data in a form that can be saved, and load and execute the script data again when necessary
n allow users to modify a script, then recompile and save the script
n redirect Apple events to script contexts
The remainder of this section provides an overview of the scripting component routines you can use to perform these tasks.
Your application can also use scripting component routines to
n get information about scripts
n get information about scripting components
n coerce script values to descriptor records and vice versa
n set a resume dispatch function and alternative send, create, and active functions for use by a scripting component
n control the recording process directly, turning recording off and on and saving the recorded script for use by your application
The chapter “Scripting Components” in this book provides detailed information about using all the standard scripting component routines as well as additional routines provided by the AppleScript component and the generic scripting component.
Compiling, Saving, Modifying, and Executing Scripts
This section introduces some of the scripting component functions your application can use to compile, save, modify, and execute scripts.
To create and execute a script using the Script Editor application, a user can type the script, then press the Run button to execute it. Your application can provide similar capabilities by using these functions to compile source data and execute the resulting compiled script:
n The OSACompile function takes a descriptor record with a handle to source data (usually text) and a script ID. If you specify kOSANullScript instead of an existing script ID, OSACompile returns a script ID for the new compiled script, which you can then pass to the OSAExecute function.
n The OSAExecute function takes a script ID for a compiled script and a script ID for a script context, executes the script, and returns a script ID for the resulting script value.
The binding of any global variables in the compiled script is determined by the script context whose script ID you pass to OSAExecute. If you pass kOSANullScript instead of the script ID for a script context, the scripting component provides its own default context. If you want to provide your own script context rather than using the scripting component default context, you can use either OSACompile or OSAMakeContext to create a script context, which you can load and store just like a compiled script.
After creating a script and trying it out, a user may want to save it for future use. Your application should normally save its scripts as script data rather than source data, so that it can reload and execute the data without recompiling it. Before saving script data, you must first call the OSAStore function to get a handle to the data in the form of a descriptor record. You can then save the data to disk as a resource or write it to the data fork of a document.
To allow a user to reload and execute a previously compiled and saved script, your application can call these functions:
n The OSALoad function takes a descriptor record that contains a handle to the saved script data and returns a script ID for the compiled script.
n The OSAExecute function takes a script ID for a compiled script and a script ID for a script context, executes the script, and returns a script ID for the resulting script value.
In most cases you will want to allow users to modify saved scripts and save them again. To allow a user to modify and save a compiled script, your application can call these functions:
n The OSAGetSource function takes a script ID and returns a descriptor record with a handle to the equivalent source data.
n The OSACompile function takes a descriptor record with a handle to source data and a script ID, and returns the same script ID updated so that it refers to the modified and recompiled script.
n The OSAStore function takes a script ID and returns a copy of the corresponding script data in the form of a storage descriptor record.
You can pass the script ID for the compiled script to be modified to the OSAGetSource function, which returns a descriptor record with a handle to the equivalent source data. Your application can then present the source data to the user for editing. When the user has finished editing the source data, you can pass the modified source data and the original script ID to the OSACompile function to update the script ID so that it refers to the modified and recompiled script. Finally, to obtain a handle to the modified script data so you can save it in a resource or write it to the data fork of a document, you can pass the script ID for the modified compiled script to the OSAStore function.
If your application has no further use for a compiled script or a resulting script value after successfully loading, saving, compiling, or executing a script, you can use the OSADispose function to release the memory assigned to them. The OSADispose function takes a script ID and releases the memory assigned to the corresponding script data. A script ID is no longer valid after the memory associated with it has been released. This means, for example, that a scripting component may assign a different script ID to the same compiled script each time you load it, and that a scripting component may reuse a script ID that is no longer associated with a specific script.
“Using Scripting Component Routines,” which begins on page 10-7, provides more information about the standard scripting component routines described in this section.
Using a Script Context to Handle an Apple Event
One way to associate a script with an object is to associate a script context with a specific Apple event object—that is, with any object in your application that can be identified by an object specifier record. When an Apple event acts on an Apple event object with which a script context is associated, your application attempts to use the script context to handle the Apple event. This approach can be useful if you want to associate many different scripts with many different kinds of objects.
Figure 7-7 illustrates one way that an application can use a script context to handle an Apple event. This example shows how you can use a general Apple event handler to provide initial processing for all Apple events received by your application. If an Apple event acts on an object with which a script context is associated, the general handler attempts to use the script context to handle the event.
The SurfWriter application in Figure 7-7 associates script contexts (called script objects in AppleScript) with geometric shapes such as circles or squares. These script contexts can contain one or more user-defined handlers for specific Apple events. For example, the script context shown in Figure 7-7 is associated with a circle and contains this handler:
on move to {x, y}
continue move to {x, item 2 of position of this}
end move
This handler exists only as AppleScript statements in the script context and doesn’t have an entry in SurfWriter’s Apple event dispatch table. SurfWriter does have its own standard Apple event handlers installed in its Apple event dispatch table. When SurfWriter receives a Move event that acts on the circle with which this script context is associated, SurfWriter uses the handler in the script context to modify its own standard handling of the event. The rest of this section describes how this works.
Figure 7-7 Using a handler in a script context to handle an Apple event
The MyGeneralAppleEventHandler function in Figure 7-7 is installed in SurfWriter’s special handler dispatch table. Thus, MyGeneralAppleEventHandler provides initial processing for all Apple events received by SurfWriter. When it receives an Apple event, MyGeneralAppleEventHandler checks whether a script context is associated with the object on which the event acts. If so, MyGeneralAppleEventHandler passes the event and a script ID for the script context to the OSADoEvent function. If not, MyGeneralAppleEventHandler returns errAEEventNotHandled, which causes the Apple Event Manager to look for the appropriate handler in SurfWriter’s Apple event dispatch table.
The OSADoEvent function looks for a handler in the specified script context that can handle the specified event. If the script context doesn’t include an appropriate handler, OSADoEvent returns errAEEventNotHandled. If the script context includes an appropriate handler (in this example, a handler that begins on move), OSADoEvent attempts to use the handler to handle the event.
When it encounters the continue statement during execution of the on move handler shown in Figure 7-7, the AppleScript component calls SurfWriter’s resume dispatch function. A resume dispatch function takes an Apple event and invokes the ap